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

user1184100
  • 6,742
  • 29
  • 80
  • 121
  • I don't why you can't have another getScript. is there any specific reason? – You Qi Feb 23 '12 at 01: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. – Reinstate Monica Cellio Feb 23 '12 at 01:50
  • i'm dynamically loading entire page - $('body').load('/bmds/pages/test.html'); - so i need to add supporting javascript files and css... – user1184100 Feb 23 '12 at 01:58

4 Answers4

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');
    });
}
Community
  • 1
  • 1
Birdman
  • 724
  • 5
  • 9
3

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

Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
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
                })
disease
  • 61
  • 2
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);  
                }
           }
Frankey
  • 3,679
  • 28
  • 25
  • 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 – hamilton.lima Jun 16 '13 at 01:34
  • 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? – Frankey Jun 16 '13 at 10:08
  • hummm tough that each $.getScript is an separated asynchronous call isn't it ? – hamilton.lima Jun 17 '13 at 14:38
  • 1
    @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... – Mischa Molhoek Nov 17 '14 at 09:26