javascript - 使用 RequireJS 加载 jQuery - 哪个更好,本地版本还是 CDN 版本?

标签 javascript jquery requirejs cdn

编辑澄清:

性能而言(尽管我知道这仍然是一个荒唐的术语),哪个更好 - 加载本地版本或 CDN 版本的 jQuery,而不是 RequireJS?

为了记录,RequireJS online doc包含一些似乎不鼓励使用 CDN 的段落,但我并不能 100% 确定它的含义:

Do not mix CDN loading with shim config in a build. Example scenario: you load jQuery from the CDN but use the shim config to load something like the stock version of Backbone that depends on jQuery. When you do the build, be sure to inline jQuery in the built file and do not load it from the CDN. Otherwise, Backbone will be inlined in the built file and it will execute before the CDN-loaded jQuery will load. This is because the shim config just delays loading of the files until dependencies are loaded, but does not do any auto-wrapping of define. After a build, the dependencies are already inlined, the shim config cannot delay execution of the non-define()'d code until later. define()'d modules do work with CDN loaded code after a build because they properly wrap their source in define factory function that will not execute until dependencies are loaded. So the lesson: shim config is a stop-gap measure for for non-modular code, legacy code. define()'d modules are better.

理论上,使用 CDN jQuery 文件会导致多 1 个 HTTP 请求(无法使用 r.js 与其他 JS 文件合并),但潜在的好处是您的访问者可能已经缓存了来自其他网站的 CDN 版本他们访问过的网站。

但是,如果我从谷歌搜索的信息中得到正确的信息,您仍然需要向 r.js 提供本地 jQuery 副本,因为生成的缩小 JS 文件将仍然需要包含 jQuery 模块的副本以确保依赖的一致性。这将导致通过本地和 CDN 加载 jQuery。 (希望我没听错?)

那么,哪种方式更好呢?

最佳答案

您的 requirejs 文档引用专门针对使用具有 jQuery 垫片配置的脚本。如果所有脚本都是 AMD 模块,则从第 3 方 CDN 动态加载基本依赖项是可以的。

缓存命中率并不像您想象的那么高(我相信 Yahoo 对缓存与非缓存状态进行了研究),这意味着现在您必须依赖另一个域来加载。

好处可能取决于应用程序,对其进行分析将得出最佳答案。例如,如果它是一个包含大量图片的网站,那么 jquery 的策略就不那么重要了,因为图片加载可能是更明显的性能问题。

我会从优化构建文件中的 jQuery 开始,并为所有内容使用 AMD 模块,所以如果我想委托(delegate)给 CDN,我可以。但是,如果使用 requirejs 和 shim 配置,则需要在构建文件中内联基本依赖项,因为填充库不调用 define()——它们不等待依赖项加载,它们希望它们立即可用。

关于javascript - 使用 RequireJS 加载 jQuery - 哪个更好,本地版本还是 CDN 版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12141871/

相关文章:

javascript - 加载所有 requirejs 模块后运行操作

javascript - 我怎样才能让点击一个按钮改变它的类名和我的 HTML 标签的类名?

javascript - 在html和jquery中隐藏一列

使用函数构造函数创建对象时javascript双重相等比较

javascript - 如何根据自定义属性分别为具有相同类的所有元素设置背景颜色

javascript - 使用 RequireJS 加载多个配置文件

javascript - jQuery-一次停止所有音频

javascript - 正则表达式用单个空格替换多个空格

javascript - createElement() 与 AJAX 响应

javascript - 使用 require 和 backbone 通过 html 文件而不是脚本标签加载模板