什么是一个好方法来尝试加载托管的jQuery在谷歌(或其他谷歌托管库),但加载我的jQuery副本,如果谷歌尝试失败?
我不是说谷歌很古怪。在某些情况下,谷歌副本会被屏蔽(例如,显然在伊朗)。
我是否会设置一个计时器并检查jQuery对象?
两份拷贝都通过的危险是什么?
并不是真的在寻找像“只用谷歌”或“只用你自己的”这样的答案。我理解这些论点。我还知道用户可能缓存了谷歌版本。我在考虑云计算的后备方案。
编辑:这部分增加了…
因为谷歌建议使用谷歌。加载加载ajax库,它执行回调时,我想知道这是否是序列化这个问题的关键。
我知道这听起来有点疯狂。我只是想弄清楚它是否能以一种可靠的方式完成。
更新:jQuery现在托管在微软的CDN上。
http://www.asp.net/ajax/cdn/
谷歌托管jQuery
如果你关心旧的浏览器,主要是IE9之前的IE版本,这是最广泛兼容的jQuery版本
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
如果你不关心老die,这个更小更快:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
备份/后备计划!
无论哪种方式,您都应该使用回退到本地,以防谷歌CDN失败(不太可能)或在您的用户访问您的网站的位置被阻止(略有可能),如伊朗或有时中国。
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>if (!window.jQuery) { document.write('<script src="/path/to/your/jquery"><\/script>'); }
</script>
参考:http://websitespeedoptimizations.com/ContentDeliveryNetworkPost.aspx
if (typeof jQuery == 'undefined')) { ...
Or
if(!window.jQuery){
将不工作,如果cdn版本没有加载,因为浏览器将通过这个条件运行,在它仍然下载剩下的javascript需要jQuery和它返回错误。解决方案是通过该条件加载脚本。
<script src="http://WRONGPATH.code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script><!-- WRONGPATH for test-->
<script type="text/javascript">
function loadCDN_or_local(){
if(!window.jQuery){//jQuery not loaded, take a local copy of jQuery and then my scripts
var scripts=['local_copy_jquery.js','my_javascripts.js'];
for(var i=0;i<scripts.length;i++){
scri=document.getElementsByTagName('head')[0].appendChild(document.createElement('script'));
scri.type='text/javascript';
scri.src=scripts[i];
}
}
else{// jQuery loaded can load my scripts
var s=document.getElementsByTagName('head')[0].appendChild(document.createElement('script'));
s.type='text/javascript';
s.src='my_javascripts.js';
}
}
window.onload=function(){loadCDN_or_local();};
</script>
你可以使用如下代码:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>window.jQuery || document.write('<script type="text/javascript" src="./scripts/jquery.min.js">\x3C/script>')</script>
但是你也可以使用一些库来为你的脚本设置一些可能的回退,并优化加载过程:
basket.js
RequireJS
yepnope
例子:
basket.js
我认为目前最好的变种。将您的脚本缓存在localStorage,这将加快下次加载。最简单的调用:
basket.require({ url: '/path/to/jquery.js' });
这将返回一个promise,你可以在错误时执行下一步调用,或者在成功时加载依赖项:
basket
.require({ url: '/path/to/jquery.js' })
.then(function () {
// Success
}, function (error) {
// There was an error fetching the script
// Try to load jquery from the next cdn
});
RequireJS
requirejs.config({
enforceDefine: true,
paths: {
jquery: [
'//ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min',
//If the CDN location fails, load from this location
'js/jquery-2.0.0.min'
]
}
});
//Later
require(['jquery'], function ($) {
});
耶普诺普
yepnope([{
load: 'http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min.js',
complete: function () {
if (!window.jQuery) {
yepnope('js/jquery-2.0.0.min.js');
}
}
}]);