我不认为官方 API 支持你想要的,但这里有一些解决方法的想法:
选项 1:将表达式嵌入到随机使用哪个 CDN 的路径配置部分。下面是 jQuery 的示例,但您可以对不同的库重复类似的操作:
<script src="js/lib/require.js"></script>
<script>
var jqCDNs = [ 'http://code.jquery.com/jquery-2.0.2', 'http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.2' ]
require.config({
paths: {
foomodule: 'libs/foo',
// create array with two elements: a random CDN url plus a local fallback version
jquery: [ jqCDNs[Math.floor(Math.random() * jqCDNs.length)], 'jquery-2.0.2' ]
}
});
require( ['jquery'], function(jq) {
// do stuff
});
选项 2:覆盖 RequireJS 的加载方法,如细粒度 URL 控制中所述:
<script src="require.js"></script>
<script>
require.config({
paths: {
foomodule: 'libs/foo',
jquery: [ '{CDN_PREFIX}/jquery-2.0.2' ]
}
});
(function () {
var CDNs = [ 'http://code.jquery.com/', 'http://ajax.aspnetcdn.com/ajax/jQuery/' ]
var load = requirejs.load;
requirejs.load = function (context, moduleId, url) {
var prefix = CDNs[Math.floor(Math.random() * CDNs.length)];
//modify url here, then call original load
url = url.replace('./{CDN_PREFIX}', prefix);
return load(context, moduleId, url);
};
require( ['jquery'], function(jq) {
// do stuff
});
}());
</script>
选项 3:编写自己的Loader Plugin。下面的示例代码不是一个完整的解决方案,但它显示了我的意思:
// normal RequireJS config stuff
require.config({
paths: {
foomodule: 'libs/foo',
jquery: [ 'http://code.jquery.com/jquery-2.0.2', 'http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.2' ]
}
});
// crud loader plug-in. See http://requirejs.org/docs/plugins.html for more things to think about
//
// RequireJS supports an array of path values but it always takes them in order
// this loader plug-in is a hack to shuffle the order before RequireJS does its request
define('cdn', function() {
//credit: http://stackoverflow.com/a/12646864/151212
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
return {
load: function (name, req, onload, config) {
// if the module has an array of path configs,
if (config.paths && config.paths[name] && config.paths[name].length && config.paths[name].length > 1) {
// shuffle the order of it
shuffleArray(config.paths[name])
}
// and then pass on to the normal RequireJS process
req([name], function (value) {
onload(value);
});
}
};
});
// then use the randPath! prefix before any module that you want to use this shuffle process
require( ['cdn!jquery'], function(jq) {
// do stuff
});