Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load a variable number of scripts with jQuery.getScript() before running javascript code?

I need to load a variable number of javascript source files before running javascript code that depends on them. Sometimes 1 script needs to be loaded, other times 2. The getScript() method allows one script to be loaded - how could I use it to load x number of scripts before running its inner code?

$.getScript("test.js", function(){
    // code to run after script is loaded
});

What I need:

$.getScript(new Array("1.js","2.js"), function(){
    // code to run after all scripts are loaded
});

Thanks

like image 497
Tom Avatar asked Feb 17 '11 22:02

Tom


People also ask

What is getScript in JS?

The getScript() method is used to get and execute a JavaScript using an AJAX HTTP GET request.

How do you check if a script is loaded with JavaScript?

Pass the URL of JavaScript file in a <script> tag. Set the onload parameter, Trigger alert if script loaded. If not then check for loaded variable, if it is equal to false, then script not loaded.

How to include other JavaScript files?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.


3 Answers

If you are using jquery 1.5 you can use the new deferred syntax.

$.when(
    $.getScript("1.js"), 
    $.getScript("2.js"), 
    $.getScript("3.js")
).then(function(){
    alert("all loaded");
});

Just pass in the scripts you wish to load.

like image 52
david Avatar answered Oct 10 '22 06:10

david


I suggest you look into LABjs

That is exactly what its purpose is.

like image 38
JAAulde Avatar answered Oct 10 '22 08:10

JAAulde


I've use RequireJS quite extensively and it's very good. However, this might work for you:

$.getScript("1.js", function(){
    $.getScript("2.js", function () {
        // code to run after all scripts are loaded
    });
});

That's a pretty nasty and little block of code there, IMO, but if it is actually only two scripts like that, it's probably worth it. The logic of the above could also be extracted to a generic function, but once you go too far down that path, it's probably smarter to use RequireJS, or LABjs as JAAulde suggested.

like image 21
nickf Avatar answered Oct 10 '22 07:10

nickf