加载jQuery插件和多个脚本最佳实践

时间:2011-03-01 22:52:19

标签: javascript jquery html

我目前正在寻找一种加载多个脚本/插件的方法,而不会在标题中列出清单。

要简单地加载一个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]);
    }
})

我目前有这样的东西,但由于某种原因无法让它工作。有什么想法吗?

4 个答案:

答案 0 :(得分:7)

你看过head.js?

吗?

答案 1 :(得分:3)

这是我对head.js的结论,我自己做了一些基准测试:

http://blog.feronovak.com/2011/03/headjs-script-is-it-really-necessary.html

这是主观意见,基准并不是科学的。

答案 2 :(得分: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");})

答案 3 :(得分: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);  
                }
           }