从 CDN 获取 jQuery?
我正在使用 require JS,并且想知道使用 CDN 版本的 jQuery 的最佳方法。我听说 1.7 版本是“AMD”,这应该有帮助,但找不到直接的例子。希望一些 RequireJS 专家可以帮助我。
I am using require JS and want to know the best method to use a CDN version of jQuery. I hear the 1.7 version is "AMD" which is supposed to help but can't find a straight example. Hope some RequireJS gurus can help me out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,建议对 jQuery CDN 使用 协议相对 URL 。
其次,如果 CND 已失效,则使用 CDN 和本地位置的值数组来加载本地文件。您可以使用任意数量的 CDN 网址。不用担心,如果从 CDN 成功下载它,它不会从本地加载第二个文件。
First of all, it's recommend use Protocol-relative URL for jQuery CDN.
And second, use array in value with CDN and local places for load local file if CND is dead. You can use as many CDNs urls you want. Do not afraid, it dosn't want load second file from local place if successfully download it from CDN.
您可以将其作为模块的依赖项包含在内,但它有点不稳定。例如,
它不太好,有两个原因
1) jquery 文件本身不是一个模块,因此从函数中获得的
$
不会是 jquery2)
order!
插件不能很好地与 CDN 版本的脚本配合使用。请参阅 Requirejs 的顺序不适用于优先级配置和 CDN 依赖项我还没有机会在“真正的”项目中使用它,因为我们还没有升级,但从我的测试中我发现最好的方法是将 jquery 包含在脚本标签,那么它可以很好地作为模块的依赖项。希望以下小样本会有所帮助:
You can include it as a dependency for a module but it's a little flakey. e.g
It's not so good for 2 reasons
1) the jquery file itself isn't a module so the
$
you get from the function won't be jquery2) the
order!
plugin doesn't work well with CDN versions of scripts. See Requirejs' order does not work with priority config and CDN dependenciesI haven't had the chance to use this in a 'real' project yet because we haven't upgraded yet, but from my tests i've found that the best way is to include jquery in a script tag, then it works great as a dependency to your modules. Hopefully the following small sample will be helpful:
@jrburke 的答案对我不起作用。根据 RequireJS api 文档,您不应在路径中包含文件扩展名。所以这是工作代码:
我在 jsfiddle 上有一个工作示例:
http://jsfiddle.net/murrayju/FdKTn/
@jrburke's answer does not work for me. According to the RequireJS api doc, you should not include the file extension in the path. So here is the working code:
I have a working example on jsfiddle:
http://jsfiddle.net/murrayju/FdKTn/
jQuery 1.7 通过名称“jquery”将自身注册为 AMD 模块,因此您需要使用路径配置为“jquery”创建映射:
但请注意,RequireJS 异步加载模块并且乱序 ,因此,如果您想要使用未包含在
define(['jquery'], function ($){ /* 插件代码位于此处 */ });
调用中的 jQuery 插件,则插件可以在 jQuery 加载之前执行。有关处理依赖于 jQuery 但不换行的文件的方法,请参阅 require-jquery 项目的 README自己在
define()
调用中。jQuery 1.7 registers itself as an AMD module by the name of 'jquery', so you need to create a mapping for 'jquery' using the paths config:
Note however that RequireJS loads modules asynchronously and out of order, so if you have jQuery plugins you want to use that are not wrapped in
define(['jquery'], function ($){ /* plugin code goes here */ });
calls, the plugin could execute before jQuery is loaded.See the require-jquery project's README on ways to deal with files that depend on jQuery but do not wrap themselves in
define()
calls.