JavaScript 延迟初始化的优点和缺点
您好,我想听听考虑 javascript 延迟初始化(仅在使用对象时加载脚本)的任何优缺点。如有任何意见,我们将不胜感激。
Hi i wanted to hear any pros and cons considering javascript lazy initialization, when script is loaded only when object is used. Any comments would be highly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
优点:在页面可读/准备好与用户交互之前启动时间较短。
缺点:使用对象时延迟较高。复杂。可能的错误来源是需要某些东西但代码尚未加载。
Pros: lower startup time before your page is readable/ready to interact with the user.
Cons: higher latency when the object is used. Complexity. Possible source of bugs where something is needed but the code has not been loaded.
我想说延迟加载脚本的最大原因是如果不完全确定该脚本将在页面上使用。
但几乎在我考虑过使用延迟加载脚本的所有情况下,我发现好处不足以超过坏处。例如,如果您需要延迟加载脚本,则大小可能不是很大。现在加载该脚本将引发另一个 HTTP 请求,并且如果该文件在开始时已被缩小和压缩,则将其与页面中包含的其他脚本捆绑在一起似乎会更有效。这将带来减少 HTTP 请求、最小化执行延迟并可能允许浏览器缓存所有脚本的好处。
不使用延迟加载还有更多好处,在我看来,在我使用的应用程序类型中延迟加载是不值得的。当然,您的情况可能有所不同。
I would say the biggest reason to lazy load a script is if it's not entirely certain that script is going to be used on the page.
But almost every situation where I have considered using lazy loaded scripts, I find that the benefits aren't enough to outweigh the cons. For instance, if you are needing to lazy load a script, chances are the size isn't very large. To load that script will now incur another HTTP request, and if the file had been minified and gzipped in the beginning, it would seem to be much more efficient to bundle it with the other scripts included in the page. This would give the benefit of reducing HTTP requests, minimizing latency of execution, and potentially allowing all of the scripts to be cacheable by the browser.
There are much more benefits to not using lazy loading as well, and in my opinion, lazy loading is just not worth it in the kinds of applications I work with. Of course, your situation might be different.