简体   繁体   English

加载一个大的 javascript 文件与多个整体大小较小的小文件的性能?

[英]Performance of loading one large javascript file vs multiple smaller files with less overall size?

I have a question regarding the loading of javascript files.我有一个关于 javascript 文件加载的问题。 From what I've read so far, the general consensus appears to be "less script files is better", but I could not find an answer to my next question:从我到目前为止所读到的内容来看,普遍的共识似乎是“脚本文件越少越好”,但我找不到下一个问题的答案:

Say you have a javascript file with 4000 lines of code, but only 500 lines of that are used on one specific page.假设您有一个包含 4000 行代码的 javascript 文件,但在一个特定页面上只使用了其中的 500 行。 Would it make sense (performance-wise) to only load this part of the script when that specific page is opened (using something like if URL == X then load {})?仅在打开特定页面时加载脚本的这部分(使用 if URL == X then load {} 之类的内容)是否有意义(性能方面)? Or would it be better if you load the entire script all at once?还是一次性加载整个脚本会更好?

(Please assume the script in question can be refactored into multiple files) (请假设有问题的脚本可以重构为多个文件)

Realistically, breaking up the javascript loaded by functionality at a granular level (~500 lines as suggested in your question) will not give you much better performance.实际上,在粒度级别(如您的问题中建议的约 500 行)分解功能加载的 javascript不会给您带来更好的性能。 You'll get a lot more benefits from combining, minifying , and optimizing your javascript.您将从组合、缩小优化您的 javascript 中获得更多好处。 Don't forget to minify your CSS as well.不要忘记缩小您的 CSS。

This will generally speed up download times because it not only reduces the number of bytes transferred (what you're focusing on), but actually makes your javascript smaller (making variable names smaller & removing whitespace), and also reduces the number of HTTP requests (this actually has a large effect on page performance).这通常会加快下载时间,因为它不仅减少了传输的字节数(您关注的内容),而且实际上使您的 javascript 更小(使变量名称更小并删除空格),并且还减少了 HTTP 请求的数量(这实际上对页面性能有很大影响)。 Check out this article for a more in depth demo of how this has an effect on speed.查看这篇文章,更深入地演示这如何影响速度。

Additionally, by always using the same combined/minified file (instead of a different one for each page in your app), you take advantage of the browser caching your script on first load, meaning after the initial load, your page gets its scripts from cache.此外,通过始终使用相同的组合/缩小文件(而不是为应用程序中的每个页面使用不同的文件),您可以利用浏览器在第一次加载时缓存您的脚本,这意味着在初始加载后,您的页面从缓存。

(Note - I linked to Google PageSpeed for optimization tips above - there is a lot more than this that is useful to know for doing js optimizations) (注意 - 我链接到 Google PageSpeed 以获得上面的优化提示 - 对于进行 js 优化,还有很多有用的知识)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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