2012-10-16 47 views
0

我想阻止我的系统多次加载相同的脚本,因为可以组合不同的模块,并使用我不想操作的第三方库。多次加载相同的javascript

有没有人做过这个?

+0

它通常依赖于网站是如何创建的,通常情况下的服务器端代码用来管理哪些资源被加载,例如与['ScriptManager.RegisterClientScript'](HTTP ://ASP.NET。microsoft。 – zzzzBov

回答

0

由于像Require JS这样的库没有解决我的问题,所以我提出了自己的解决方案,我在下面发表。

我的系统也是由不同的模块组成。在主模块中,我有一个用于所有模块(php,js和css文件)依赖关系的加载器。在加载依赖关系之后,应用程序将触发一个事件并设置一个全局变量来防止文件的双重包含。

希望它有帮助。如果您有任何疑问,请告诉我。

的代码:

//Main 
var main = { 
    init: function(){ 
     //Dependencies to load (php, js or css) 
     var deps = [ 
      '/helpers/edit/v/edit.php',     
      '/helpers/edit/css/edit.css',    
      '/helpers/validate/js/jquery.validate.js,messages_pt_BR.js' 
     ];   
     //Load initial pack 
     if (!window.editReady){ 
      //Load dependencies 
      this.load('edit',deps);   

      //Bind loaded event 
      $('body').on('editReady',function(){ 
       //Set editLoaded to avoid double ajax requests 
       window.editReady = true; 

       //Do whatever you need after it's loaded 

      }); 
     } 
    }, 
    //Load external resources 
    load: function(name,data_urls){ 
     var url, ext; 
     var len = data_urls.length; 
     var i = 0; 
     $(data_urls).each(function(){ 
      //Get proper file 
      $.get(this, function(data) { 
       url = this.url; 
       ext = url.split('.').pop(); 
       switch(ext){ 
        case 'php': 
         this.appended 
         $(data).appendTo('body'); 
         break; 
        case 'css': 
         $('<link/>') 
         .attr({ 
          'rel':'stylesheet', 
          'href':url 
         }).appendTo('head'); 
         break; 
       } 
       //Check if all files are included 
       i += 1; 
       if (i == len) { 
       $("body").trigger(name+"Ready"); 
       } 
      }); 
     }); 
    } 
}; 

var modules = { 
    themes : { 
     init : function(){ 
      //Load dependencies 
      var deps = [ 
       '/helpers/plupload/js/plupload.js,plupload.html5.js,plupload.flash.js' 
      ];   
      if (!window.themesReady){ 
       //Set themesReady to avoid double ajax requests 
       window.themesReady = true; 

       //Load dependencies 
       main.load('themes',deps); 

       $('body').on('themesReady',function(){ 

        //Do whatever you need after it's ready 
       }); 
      } 
     } 
    } 
}  
main.init(); 
4

RequireJS怎么样?似乎是你在找什么。