gpt4 book ai didi

javascript - 避免使用 requirejs 加载已经注入(inject)到 DOM 中的模块

转载 作者:搜寻专家 更新时间:2023-11-01 04:32:16 24 4
gpt4 key购买 nike

有没有办法避免加载可能已经存在于 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: {
'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 发送了拉取请求 https://github.com/jrburke/requirejs/issues/886以我的提议。固定版本的 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'
}
}
});

最佳答案

正如@jrburke 在您的 pull-request 中指出的那样,实现方式是:

require.config({});

if (typeof jQuery === 'function') {
define('jquery', function() { return jQuery; });
}

// start module loading here
require(['app'], function(app) {});

如果一个模块已经被定义,它不会被(重新)加载。在这里,定义只是简单地重新使用已经加载的全局 jQuery 对象。

关于javascript - 避免使用 requirejs 加载已经注入(inject)到 DOM 中的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18913540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com