0

I want to prevent my system from loading the same script more than once, because different modules can be combined and I use third party libraries that I don't want to manipulate.

Has anyone done this before?

4

2 に答える 2

4

RequireJSはどうですか?あなたが探しているもののようです。

于 2012-10-16T19:58:25.443 に答える
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();
于 2012-10-16T20:48:58.887 に答える