Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid loading modules already injected into the DOM with requirejs

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'
    }
  }
});
like image 538
Gianluca Guarini Avatar asked Nov 01 '22 14:11

Gianluca Guarini


1 Answers

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.

like image 177
Peter V. Mørch Avatar answered Nov 09 '22 03:11

Peter V. Mørch