How to load specific JS files using RequireJS?

I have a multi-page website using RequireJS that downloads a boot belt file (boot.js), which then requires app.js.

app.js handles all the logic, and all other module initialization happens through app.initModule () (which is just the shell of the require () call)

I also have app.loadPageJS () for loading specific JS files on the page (based on window.location.pathname, for example, www.domain.com/path/to/file.html will automatically load / _assets / JS / pages / path / to / file.js)

This function can be turned on / off and overridden by adding the class "no-auto-load" or "auto-load" to the body, respectively.

Now my approach is not strong enough. Firstly, rewriting URLs will break the mechanism, and for two, if loadPageJS is disabled, if I do not have access to the body tag, I cannot include a page-specific JS file (in the case of sites using template systems, adding the class for the body tag is not always an option).

What are other ways to include page code? I would rather avoid the following:

  • adding special page code to the global.js file and executing if checking and executing only certain code sets

  • using the pageName variable (which will essentially be similar to the one above)

Thanks in advance.

+4
source share
1 answer

If you have different modules on a page separated by a unique identifier (a news module wrapped in a div with the identifier of a “newsletter”, etc.), you can check for the presence of a module element in the DOM and conditionally load it into the JS file needed to run of this module. Thus, instead of being page specific, it is module specific.

0
source

Source: https://habr.com/ru/post/1401925/


All Articles