Javascript 避免加载已使用requirejs注入DOM的模块
有没有办法避免将可能已经存在的模块加载到DOM中 例如:Javascript 避免加载已使用requirejs注入DOM的模块,javascript,requirejs,amd,Javascript,Requirejs,Amd,有没有办法避免将可能已经存在的模块加载到DOM中 例如: require.config({ paths: { // jquery here is needed only if window.jQuery is undefined 'jquery': '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min' } }); 如果能够使用像这样的代码片段,那就太好了 require.config({ paths:
require.config({
paths: {
// jquery here is needed only if window.jQuery is undefined
'jquery': '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min'
}
});
如果能够使用像这样的代码片段,那就太好了
require.config({
paths: {
'jquery': {
uri: '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min',
// if this function returns false or undefined load the script from the url
define: function(){ return window.jQuery; }
}
}
});
-----------------------------------------------------------------
更新
-----------------------------------------------------------------
我向github上的@jrburke发送了一个请求,并附上了我的建议。requirejs的固定版本可以在以下位置进行测试:
这里是根据我的API建议的requirejs配置
require.config({
paths: {
// jquery here is needed only if window.jQuery is undefined
'jquery':'//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min',
'lodash':'//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.0.0/lodash.underscore.min',
'backbone':'//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min'
},
shim:{
'jquery':{
// with my fix now I detect whether window.jQuery has been already defined
// in this case I avoid to load the script from the cdn
exports:'jQuery',
// if this feature is missing I need to load the new jQuery from the cdn
validate: function(){
return window.jQuery.Defferred;
}
},
'lodash':{
// lodash will be loaded only if it does not exist in the DOM
exports:'_',
// if this function returns false or undefined load the script from the cdn
validate: function() {
// is the lodash version already available in the DOM new enough for my application?
return window.parseInt(window._.VERSION) >= 2;
}
},
'backbone':{
deps:['lodash','jquery'],
// if backbone exists we don't need to load it twice
exports:'Backbone'
}
}
});
由于jQuery与AMD兼容,如果它已经在页面中,Require.js将不会再次加载它 更广泛地说,Require.js只在模块尚未定义时查看配置的路径。因此,一旦定义了模块,Require.js就不会再次加载它:
define('jquery', [], function() { /* stuff */ });
// ^ Module 'jquery' is defined here. Require.js won't load it twice.
签出此JsBin以获得一个工作示例:正如@jrburke在您的文章中指出的那样,这样做的方法是:
require.config({});
if (typeof jQuery === 'function') {
define('jquery', function() { return jQuery; });
}
// start module loading here
require(['app'], function(app) {});
如果模块已定义,则不会(重新)加载该模块。在这里,定义只是重复使用已经加载的全局
jQuery
对象。我不能100%确定这是否可行。。让我来测试一下first@GianlucaGuarini你的URL不起作用。在这里,检查这个JsBin:也许您在Require.js库之前加载了jQuery。在这种情况下,jQuery当然无法注册一个模块,因为Require还不可用。对不起,这里让我更明确一点:我需要开发一个可以在没有requirejs的情况下使用的模块;因此,我的模块将使用almondjs构建,使其在任何环境中都可用(即使是非amd环境)。如果我的模块依赖于主干网、lodash和jQuery,我需要在某个地方下载这些依赖项:如果托管模块的页面中已经使用了其中一个依赖项,我将使用它,否则我需要从cdn下载不可用的依赖项。希望现在这个概念更清晰:)我创建了一个简单的测试,向您展示同一应用核心库的不同版本的问题