2011-03-01 48 views
5

我目前正在尋找一種方法來加載多個腳本/插件,而無需在標題中列出洗衣列表。加載jQuery插件和多個腳本最佳實踐

要簡單地有一個load.js有一切加載在我會很優雅。

$(function() { 
    var scripts = ['scripts/jquery1.5.js','scripts/easing.js','scripts/scroll.js','scripts/main.js']; 

    for(var i = 0; i < scripts.length; i++) { 
     $.getScript(scripts[i]); 
    } 
}) 

我目前有這樣的事情,但不能因爲某種原因讓它工作。有任何想法嗎?

回答

1

這是我的解決方案:檢查文件是否被添加(存儲在數組中),然後一個接一個地加載一個文件。完美的作品!

var filesadded = "" //list of files already added 
function loadJSQueue(array, success) { 

    if (array.length != 0) { 
     if (filesadded.indexOf("[" + array[0] + "]") == -1) { 
      filesadded += "[" + array[0] + "]" //List of files added in the form "[filename1],[filename2],etc" 

      oHead = document.getElementsByTagName('head')[0]; 
      var oScript = document.createElement('script'); 
      oScript.type = 'text/javascript'; 
      oScript.src = array[0]; 
      array.shift(); 
      oScript.onreadystatechange = function() { 
       if (this.readyState == 'complete') { 
        loadJSQueue(array, success); 
       } 
      } 

      oHead.appendChild(oScript); 
     } 
     else { 
      array.shift(); 
      loadJSQueue(array, success); 
     } 

    } 
    else { 
     success(); 
    } 
} 

loadJSQueue(["../../JavaScript/plupload/js/jquery.plupload.queue/jquery.plupload.queue.js", 
       "../../JavaScript/plupload/js/plupload.js", 
       "../../JavaScript/plupload/js/plupload.html4.js" 
       ], function(){alert("success");}) 
0
 loadScripts(['script1.js','script2.js'], function(){ alert('scripts loaded'); }  

    function loadScripts(scripts, callback){ 

       var scripts = scripts || new Array(); 
       var callback = callback || function(){}; 

       for(var i = 0; i < scripts.length; i++){ 
       (function(i) { 
        $.getScript(scripts[i], function() { 

         if(i + 1 == scripts.length){ 
         callback(); 
         } 
        }); 
        })(i); 
       } 
      } 
調用它