开发者

Should Javascript be separated into files by page or consolidated into one file?

开发者 https://www.devze.com 2022-12-24 02:52 出处:网络
Should I be separati开发者_如何学Pythonng my js for each page assuming there is no overlap and putting references on each page instead of having one master file? what is typical practice? thanksEveryt

Should I be separati开发者_如何学Pythonng my js for each page assuming there is no overlap and putting references on each page instead of having one master file? what is typical practice? thanks


Everything that is common to every page of your site should be on a single file, since it will be loaded only once by the browser.

Code specific for a single (or maybe 2) page(s) should go on separate files, loaded only by the pages that need them.

That's the way I do it: you use the browser's cache to reduce your bandwidth and to accelerate the loading and rendering of the page.


For infrequently accessed pages, load the javascript inline (at bottom of all the markup) for quickest load time (one less TCP connection required as is the case for separate .js script file).

For frequently hit pages do the opposite: reference a .js script file - in this case the caching by the browser provides a greater advantage across the aggregate of page loads.

In larger projects, develop your javascript in separate .js files (you can use the module pattern for instance), then for production compile them into a single file (or a number of files per architecture of your application) with a build script.


It all depends on what kind of app you have. If your app is frequently accessed but for short periods of time then initial loading time is important and you should try to combine files.

If, however, you expect users to spend hours at a time in your app and initial load time is not critical then I would advise partitioning your .js files as much as you need to to make it readable - since they will all be cached anyway after the initial load.

Don't believe the hype. Unless you're a google search engine you should be careful not to sacrifice readability for the sake of a few seconds (or less) at initial start up. Put it another way, rules of thumb are just that, don't neurotically follow them - think first :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号