组织 JavaScript 文件的最佳方式

发布于 2024-10-10 06:53:16 字数 199 浏览 8 评论 0原文

所以我有一个带有多个 JS 文件的 Web 应用程序(jQuery、jQuery、我自己的 JS 代码等等)。假设我有一个名为index.html 的页面。包含/预加载我的 js 文件的最佳实践是什么?我正在考虑创建一个单独的 JS 文件来执行预加载(包括所有其他脚本并调用 jQuery.noConflict())。你们有什么建议?这可能吗?你会如何实施它?

谢谢!

So I have web app with multiple JS files (jQuery, jQuery, my own JS code and more). Say I have a page named index.html. What would be the best practice to include / preload my js files? I was thinking about creating a separate JS file that will do the preloading (include all the other scripts and call jQuery.noConflict()). What do you guys suggest? Is this possible? How would you implement it?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

匿名。 2024-10-17 06:53:16

一般来说,将脚本文件合并为一个文件(以及 minify压缩它们,甚至编译< /a> 它们,但请注意,最后一项不是零影响,存在痛点)。请参阅此处这里。基本上,您将看到的快速页面加载的首要准则之一是“最小化 HTTP 请求”。因此,您不需要六个单独的 script 标记,而您可以拥有一个标记。

不过,对于流行的脚本,您可能会受益于使用 Google 的 CDN 中的脚本。 Google 非常友善地在其 CDN 上免费托管最流行的 JavaScript 库。这里的优势不仅在于 CDN 相当快,而且目标用户的浏览器很可能拥有您想要使用的脚本的缓存版本,即使他们从未访问过您的网站前。

In general, combine your script files into one file (and minify or compress them, or even compile them, but note that this last item is not zero-impact, there are pain points). See notes here and here. Basically, one of the first guidelines you'll see for a good fast page load is "minimize HTTP requests." So you don't want six separate script tags where you could have one.

For popular scripts, though, you may benefit from using them from Google's CDN. Google is kind enough to host most popular JavaScript libraries on their CDN for free. The advantage here being not only that the CDN will be fairly fast, but that the target user's browser may well have a cached version of the script you want to use even though they've never been to your site before.

冷情 2024-10-17 06:53:16

查看 RequireJS,这是一个智能且强大的 JavaScript 脚本加载器。它旨在与 jQuery 良好配合,并附带一个优化工具,可将所有脚本合并为一个。

Check out RequireJS, a smart and robust script loader for JavaScript. It's designed to work well with jQuery and comes with an optimization tool to combine all of your scripts into one.

人心善变 2024-10-17 06:53:16

最好的方法是最小化所有js文件并将它们合并到一个脚本中。这将减少浏览器的工作量,因为它不必向服务器发出多个请求。

The best way is to minimize all the js files and combine them into one script. This will cause less work for the browser, as it doesn't have to make multiple requests to the server.

岁月打碎记忆 2024-10-17 06:53:16

如果您要同时加载所有内容,您可以将其全部放入一个压缩文件中

If you are going to load everything up at the same time, you could put it all into a single compressed file

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