开发者

Loading jQuery plugins and multiple scripts best practices

I'm currently looking for a way to load in multiple scripts/plugins without having a laundry list listed out in the header开发者_如何学JAVA.

To simply have a load.js have everything load in would be very elegant to me.

$(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]);
    }
})

I currently have something like this but can't get it to work for some reason. Any ideas?


Have you looked at head.js?


Here is my conclusion for head.js, I have done some benchmarks myself:

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

It is subjective opinion and benchmarks are not by any means scientific.


This is my solution : check if file is added (stored in array) and then load one file after another. Works perfectly!

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();
    }
}

call it with

    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");})


     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);  
                }
           }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜