JavaScript 延迟初始化的优点和缺点

发布于 2024-10-18 14:01:39 字数 68 浏览 6 评论 0原文

您好,我想听听考虑 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一笑百媚生 2024-10-25 14:01:39

优点:在页面可读/准备好与用户交互之前启动时间较短。

缺点:使用对象时延迟较高。复杂。可能的错误来源是需要某些东西但代码尚未加载。

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.

离不开的别离 2024-10-25 14:01:39

我想说延迟加载脚本的最大原因是如果不完全确定该脚本将在页面上使用。

但几乎在我考虑过使用延迟加载脚本的所有情况下,我发现好处不足以超过坏处。例如,如果您需要延迟加载脚本,则大小可能不是很大。现在加载该脚本将引发另一个 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文