避免使用requirejs加载已经注入DOM的模块

时间:2013-09-20 09:42:29

标签: 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: {
    '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 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'
    }
  }
});

2 个答案:

答案 0 :(得分:2)

正如@jrburke在pull-request中指出的那样,做到这一点的方法是:

require.config({});

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

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

如果已定义模块,则不会(重新)加载。在这里,定义只是重用已经加载的全局jQuery对象。

答案 1 :(得分:0)

由于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以获取一个工作示例:http://jsbin.com/OfIBAxA/2/edit