Is there a way to avoid loading modules that could already exist into the DOM?
Example:
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'
}
});
It would be great to be able to use something like this snippet
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; }
}
}
});
UPDATE
I sent a pull request to @jrburke on github https://github.com/jrburke/requirejs/issues/886 with my proposal. The fixed version of requirejs could be tested on here:
http://gianlucaguarini.com/experiments/requirejs/requirejs-test3.html
Here the requirejs configuration according to my API proposal
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'
}
}
});
As @jrburke points out in your pull-request, the way to do it is:
require.config({});
if (typeof jQuery === 'function') {
define('jquery', function() { return jQuery; });
}
// start module loading here
require(['app'], function(app) {});
If a module is already defined, it won't be (re)loaded. Here, the definition is simply to re-use the already-loaded global jQuery
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With