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
The getScript() method is used to get and execute a JavaScript using an AJAX HTTP GET request.
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.
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.
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.
I suggest you look into LABjs
That is exactly what its purpose is.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With