// The code in this file will load on every page of your site
This is already your answer!
Your code is placed in your —> “masterPage.js”
But your used elements are on different pages.
Switching to page-1 you have different elements, as when you would switch to page-2, where you will have some other elements.
So it is not a surprise, that you gets errors, because the code on your master-page also acts like a mastercode, for all pages, but can not find the needed elements on every of your pages.
This would be my (quick-brainstorm) conclusion.