如果未加载,则从外部源加载 jQuery
从源加载 jQuery
我喜欢做的是删除本地 jquery.js 并拥有 它托管在其他地方。但如果谷歌宕机了怎么办?所以 让我们编写一个使用其他源的后备代码,如果 jQuery “仍然”未加载...
我做了这个测试用例,但它似乎不起作用,也许 有人可以帮助我:
load jQuery from source
What I like to do is to drop my local jquery.js and have
it hosted somewhere else. But what if Google is down? So
let's code a fallback that uses another source if jQuery
is "still" not loaded...
I made this test case but it does not seem to work, maybe
someone can help me out:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这工作得相当好(来自 HTML5 Boilerplate):
This works fairly well (from HTML5 Boilerplate):
这是一个纯 JavaScript 解决方案,首先检测 jQuery 是否可用。如果没有,它会尝试 CDN 版本。如果该版本不可用,它将尝试本地版本。处理 404 错误。我在一个不知道该网站是否包含 jQuery 的解决方案中使用它。
Here is a pure javascript solution that starts out by detecting if jQuery is available. If not, it tries the CDN version. If that's not available, it tries the local version. Handles 404 errors. I use this in a solution that doesn't know whether the website has included jQuery.
您的脚本的问题在于您没有等待脚本加载然后测试 jQuery 是否已加载。使用类似这样的东西:
The problem with your script is that you're not waiting for the script to load before testing whether jQuery has been loaded. Use something like this instead:
问题
如果您使用 Firebug 并查看 jQuery 的加载位置,您可以看到 Google 已成功加载它。为什么它似乎不起作用?因为请求是异步的,并且当您的脚本同步运行时,它会在加载第一个脚本之前执行所有步骤。
所以:
等等。
解决
方案 您应该做的是附加到您的
onLoad
事件脚本加载元素并在加载后检查 jQuery。与向互联网上的某个服务器发送请求并获取结果进行处理相比,脚本的执行速度快如闪电。
附加说明
正如我所读到的,您在使用此技术检测 404 时会遇到问题。建议的方法是使用 Ajax (XHR),然后附加脚本元素并向其中添加收到的内容。对于所有浏览器来说,这将是最可靠的方法。
The problem
If you use Firebug and see where jQuery gets loaded you can see taht Google successfully loaded it. Why it doesn't seem to work? Because requests are asynchronous and while your script runs synchronously it executes all steps before the first script gets loaded.
So:
etc etc.
Solution
What you should do is attach to
onLoad
event of your script loading elements and check for jQuery after they've loaded.Script executes lightning fast compared to sending a request out to some server on the internet and getting results back for processing.
Additional notes
As I've read you're going to have problems detecting 404s using this technique. Suggested way would be to use Ajax (XHR) and then attach script element and add received content to it. This would be the most reliable way of doing it for all browsers.
罗杰的回答很荒谬。在这里,使用它,它的两行。
Roger's answer is rediculous. Here, use this instead, its 2 lines.