Gia*_*ini 5 javascript amd requirejs
有没有办法避免加载已存在于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'
}
});
Run Code Online (Sandbox Code Playgroud)
能够使用这个片段之类的东西会很棒
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; }
}
}
});
Run Code Online (Sandbox Code Playgroud)
UPDATE
我和我的提议在github https://github.com/jrburke/requirejs/issues/886上向@jrburke发送了拉取请求.requirejs的固定版本可以在这里测试:
http://gianlucaguarini.com/experiments/requirejs/requirejs-test3.html
这里根据我的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'
}
}
});
Run Code Online (Sandbox Code Playgroud)
由于 jQuery 与 AMD 兼容,如果它已经在页面中,Require.js 将不会再次加载它。
从更广泛的角度来说,Require.js 仅在模块尚未定义时才查看路径配置。因此,一旦定义了模块,Require.js 就不会再次加载它:
define('jquery', [], function() { /* stuff */ });
// ^ Module 'jquery' is defined here. Require.js won't load it twice.
Run Code Online (Sandbox Code Playgroud)
查看此 JsBin 以获取工作示例:http ://jsbin.com/OfIBAxA/2/edit
| 归档时间: |
|
| 查看次数: |
3572 次 |
| 最近记录: |