简体   繁体   中英

Defer parsing/loading of Javascript

This may be a case of premature optimization or it may be a "it depends" thing... But is there a way to defer parsing/execution of parts of a Javascript until those parts of the code can be proven to be required?

In my case, I am using the Rails asset pipeline which conveniently assists in bundling/minifying all my JS into a single file. However, it is my understanding that this file needs to be loaded anew on each page load. But parts of the file are only used on certain pages.

My modules are coded using the following pattern:

(function (window, undefined) {
... all code here ...
})(window);

What I would love is a way to wrap each of those modules such that they are only parsed/loaded/executed on pages where they are needed, such as by finding a <div class='use-module-x'> tag in the DOM.

I know I can do an if/then in my module's init function to prevent it from trying to initialize itself when it's not needed, but it seems like it would be even better to just avoid having the JS engine consider this code at all when it's not needed.

Even if this isn't a real concern, I'm curious if/how it can be done.

I think what you are looking for is exactly what require.js provides . Using a convention-based approach, you can define modules of code that will be imported into the page in a managed fashion. See the getting started guide and the api reference .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM