2

i use the below code to dynamically load js scripts

$.getScript("/../../site/js/test.js").done(function(script, textStatus) {

    console.log("test.js :: " + textStatus );
});

What should i do if i want to load multiple scripts files in same piece of code instead of writing another getScript .. example test2.js , test3,js

3
  • I don't why you can't have another getScript. is there any specific reason? Commented Feb 23, 2012 at 1:49
  • I was about to answer that you do have to write more getScript commands, but I wanted to ask first why you don't want to do that. Are you simply trying to cut down on the amount of code? If so then it's 1 getScript for each script and that's just the way it works. Commented Feb 23, 2012 at 1:50
  • i'm dynamically loading entire page - $('body').load('/bmds/pages/test.html'); - so i need to add supporting javascript files and css... Commented Feb 23, 2012 at 1:58

4 Answers 4

6

Well, if you're going to have to write .getScript for each file, this is a clean way to do it. It'll also allow to build a list of files to load.

Loading scripts using jQuery

var scripts = ['plugin.js', 'test.js'];
for(var i = 0; i < scripts.length; i++) {
    $.getScript(scripts[i], function() {
        alert('script loaded');
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much ,its really helpful with multiple files.
3

I would suggest using an existing loader framework instead of writing your own. Take a look at RequireJS: http://requirejs.org/

Comments

1

// multiple browser compatible and deoesnt load same script twice.

var filesadded = ""
    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"
                var callbackCalled = false;
                oHead =  document.getElementsByTagName("head")[0] || document.documentElement;
                var oScript = document.createElement('script');
                oScript.type = 'text/javascript';
                oScript.src = array[0];
                array.shift(); //                    $(oScript).ready(function () {  //                     //              }) //                    oScript.onload = oScript.onreadystatechange = function () { //                        if (!this.readyState || this.readyState == 'complete') { //                       //           loadJSQueue(array, success); //                        } //            };

                var done = false;

                // Attach handlers for all browsers
                oScript.onload = oScript.onreadystatechange = function () {
                    if (!done && (!this.readyState ||
        this.readyState === "loaded" || this.readyState === "complete")) {
                        done = true;

//                            jQuery.handleSuccess(null, xhr, status, data); //                            jQuery.handleComplete(null, xhr, status, data);

                        // Handle memory leak in IE
                        oScript.onload = oScript.onreadystatechange = null;
                        if (oHead && oScript.parentNode) {
                            oHead.removeChild(oScript);
                        }

                        loadJSQueue(array, success);
                    }
                };

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

    }


//   usage:    
                        loadJSQueue(["../../JavaScript/plupload/js/jquery.plupload.queue/jquery.plupload.queue.js",
                "../../JavaScript/plupload/js/plupload.js",
                "../../JavaScript/plupload/js/plupload.html4.js",
                "../../JavaScript/plupload/js/plupload.html5.js"
                ], function () {
                     //do your after load stuff here
                })

Comments

1

This is the best way to load js files async.

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

4 Comments

how to make sure the scripts will be loaded in the order you called ? the first one can take longer than the first, and the condition i+1 == scripts.length wont be correct
If you loop through a array and starts with key 0, en increment with 1, than you have a order your want right? because of the (function(i) {})(i); it waits till everything is done and than proceed, have you tried it?
hummm tough that each $.getScript is an separated asynchronous call isn't it ?
@hamilton.lima, you are right, the i+1==scripts.length will only ensure the last script is loaded, the other ones might still be busy...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.