I connect to the JavaScript site with one file, it contains functions for initializing the carousel, lightbox, Yandex card and so on. All code (except for certain functions) lies in document.ready (jQuery is connected).

Naturally, not all parts of the code are used on all pages. Say, the carousel is needed only on the main one, and the map is only in the "contacts". As I understand, all the code works on all pages. Does it make sense to insert checks for the presence of certain elements, say, initialize the carousel only if there is a div with id=#fotorama , or just connect different js to different pages? Or does js / jQuery automatically perform these checks and this does not affect the speed / reliability of the scripts?

  • What does it mean: I connect to the JavaScript site with one file ? - Grundy
  • one
    On a good page, only those modules that are actually used there should be connected. That is, you need to connect different js to different pages. I advise you to look at RequireJS to solve this problem. - Alex Krass
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

The most correct way to do so (IMHO):
In the templates of each page, specify dependencies for only the necessary modules (for example, the contact template may require a map script), then, either in the View form all modules in <script></script> , or put a link of the form: http://site/js/maps,type=earth;bla-bla-bla and a separate handler for a browser request to collect and give code from files.

    There is no sense to divide into different files, it will be harder to support later.

    As the official website says, jQuery will not give an error in the absence of an element, but it is still best to check it. Since this library is waiting for all elements to be loaded before running their scripts, it is enough to check this: if (element.length){ ... } - element is a block that needs to be checked for presence on the page, and already within the condition write a script for interaction with a block.

    Pure Javascript is checked differently, for example, like this: if ( element != null ) { ... } , it does not check itself and will generate an error that the object was not found on the page.

    • A check for 0 elements is already built in, so it makes no sense to write it separately - Grundy