使用 Google 托管 jQuery 的最佳方式,但退回到我在 Google 上的托管库失败

人气:768 发布:2022-10-16 标签: jquery cdn google-ajax-libraries

问题描述

尝试加载 Google 托管的 jQuery(或其他 Google 托管的库),但如果 Google 尝试失败,请加载我的 jQuery 副本?

What would be a good way to attempt to load the hosted jQuery at Google (or other Google hosted libs), but load my copy of jQuery if the Google attempt fails?

我并不是说 Google 不稳定.在某些情况下,Google 副本会被屏蔽(例如,显然在伊朗).

I'm not saying Google is flaky. There are cases where the Google copy is blocked (apparently in Iran, for instance).

我要设置一个计时器并检查 jQuery 对象吗?

Would I set up a timer and check for the jQuery object?

两个副本都通过会有什么危险?

What would be the danger of both copies coming through?

并不是真的在寻找诸如只使用 Google 的"或只使用你自己的"之类的答案.我理解这些论点.我也知道用户很可能缓存了 Google 版本.我正在考虑一般云的后备方案.

Not really looking for answers like "just use the Google one" or "just use your own." I understand those arguments. I also understand that the user is likely to have the Google version cached. I'm thinking about fallbacks for the cloud in general.

此部分已添加...

由于 Google 建议使用 google.load 加载 ajax 库,并在完成后执行回调,我想知道这是否是序列化此问题的关键.

Since Google suggests using google.load to load the ajax libraries, and it performs a callback when done, I'm wondering if that's the key to serializing this problem.

我知道这听起来有点疯狂.我只是想弄清楚它是否可以以可靠的方式完成.

I know it sounds a bit crazy. I'm just trying to figure out if it can be done in a reliable way or not.

更新:jQuery 现在托管在 Microsoft 的 CDN 上.

Update: jQuery now hosted on Microsoft's CDN.

http://www.asp.net/ajax/cdn/

推荐答案

可以这样实现:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>

<script>
       window.jQuery || document.write('<script src="/path/to/your/jquery"></script>');
</script>

这应该在您页面的 <head> 中,并且任何 jQuery 就绪事件处理程序都应该在 <body> 中以避免错误(尽管它不是傻瓜-证明!).

This should be in your page's <head> and any jQuery ready event handlers should be in the <body> to avoid errors (although it's not fool-proof!).

不使用 Google 托管的 jQuery 的另一个原因是,在某些国家/地区,Google 的域名被禁止.

One more reason to not use Google-hosted jQuery is that in some countries, Google's domain name is banned.

770