简体   繁体   中英

What is the best way to organize JS code to best performance?

I would like to learn what is the best way to organize the JS code.

In my application have jQuery dependency and have some plugins that I use in specific pages, like:

Page 1 needs:

- jquery
- magnific-popup
- autosize
- owl.carousel

Page 2 needs:

- jquery
- magnific-popup
- autosize
- photoswipe
- verlok
- tinyColorPicker
- ZebraDatePicker
- rangeslider
- dropzonejs

Page 3 needs:

- jquery
- magnific-popup
- verlok

Is preferable to do a mega bundle with all dependency and load that in all pages.

or

Import jQuery in all pages and create a specific bundle for each page?

or

Include jQuery in specific bundle for each page and load one just file for each page?

You can create a bundle that contains dependency which all pages need (jquery and magnific popup) and create separate bundles for three pages which will load async when that page is loaded. This would improve the page load times. Other thing that you do is pre fetch the bundles. What prefetch does is load the assets in idle time. So when you load new page resources of it would be already loaded.

Hence by this approach your initial page load time is reduced and subsequent pages are also loaded faster.

I would suggest you use some module bundler like webpack which will make this take care of this for you.

It's generally better to let the client download fewer files, meaning one file would be better off. However, if you plan on changing some of the files (or updating dependencies) frequently it could be better to keep those files in a separate bundle.

You can see a more in depth discussion here .

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