我们有一个使用多个第三方JavaScript库的网站,如果可能,我们希望从CDN服务它们以减少我们服务器上的请求数量。最近,我们的一位客户报告了使用我们网站的问题,事实证明这是因为他们阻止了我们使用的一个CDN(ajax.aspnetcdn.com!)。我们一直在考虑为CDN实施故障转移,但是从来没有这样做,现在我的经理正在推动我们尽快解决它。
通常情况下,Scott Hanselman的blog似乎提供了一些潜在的答案,建议像yepnope和RequireJS这样的工具。 Yepnope已被弃用,因此我们选择RequireJS。
我们已经在我们的网站上实施了RequireJS(不是一项巨大的工作),只是发现它在IE中运行不正常(在所有其他主流浏览器中绝对完美)。
根据文档(以及此处其他帖子的一些建议),我们将其设置如下。我们在html head标签中有这个脚本标记:
<script data-main="/Scripts/main.js" src="/Scripts/require.js" type="text/javascript"></script>
然后在main.js
我们配置了RequireJS
requirejs.config({
enforceDefine: true,
paths: {
jquery: [
"https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min",
"jquery"
],
jqueryui: [
"https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min",
"jqueryui"
],
jqueryunobtrusiveajax: [
"https://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.min",
"jqueryunobtrusiveajax"
],
jqueryvalidate: [
"https://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min",
"jqueryvalidate"
],
jqueryvalidateunobtrusive: [
"https://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min",
"jqueryvalidateunobtrusive"
],
site: [
"site"
],
localisation: [
"localisation"
]
},
shim: {
jqueryui: {
deps: ['jquery'],
exports: "$"
},
jqueryvalidate: {
deps: ['jquery'],
exports: '$'
},
jqueryvalidateunobtrusive: {
deps: ['jquery', 'jqueryvalidate'],
exports: '$'
},
jqueryunobtrusiveajax: {
deps: ['jquery'],
exports: '$'
},
localisation: {
deps: ['jquery', 'jqueryui', 'jqueryvalidate'],
exports: '$'
},
site: {
deps: ['jquery', 'jqueryui', 'jqueryvalidate', 'jqueryvalidateunobtrusive'],
exports: '$'
}
}
});
请注意,根据有关如何在RequireJS的GitHub Wiki中“捕获IE中的加载失败”的建议,我们已将enforceDefine
设置为true
,并使用define()
来定义在使用require()
之前,模块(我们希望每页上都有相同的脚本),如下所示:
define('main', ["jqueryui", 'jqueryvalidate', 'jqueryvalidateunobtrusive', 'jqueryunobtrusiveajax', 'localisation', 'site'], function () {
// we have some code here that confirms each script is loaded, looks a bit like this (one for each script):
if (jQuery) {
console.log("jQuery");
} else {
console.error("jQuery");
}
});
然后在每个页面上我们只需添加以下脚本标记:
<script type="text/javascript">
require(["main"], function() {
// any page specific script goes here
});
</script>
这适用于所有浏览器(包括IE),但如果阻止任何CDN,它在IE中不起作用。奇怪的是,如果您将CDN文件的URL更改为不存在的内容,或者完全删除CDN URL(因此只需提供本地文件),它就可以正常工作。如果我通过在IE中将域添加到internet options -> security -> restricted sites
来阻止CDN,则尝试加载脚本需要很长时间(5-10秒),然后在两个本地文件上超时(site.js和localisation.js ):
SCRIPT5022: Load timeout for modules: localisation,site http://requirejs.org/docs/errors.html#timeout
如果我阻止CDN(使用AdBlock Plus),所有其他浏览器都可以正常应对,有没有人知道为什么我在IE中遇到这种行为?