Search code examples
javascriptjquerygetscript

What's the best way to execute something only when all my JavaScript is loaded using jQuery?


I'm developing a web page using jQuery, and I want it to execute some code only after ALL my JavaScript files are fully loaded. The head section of my HTML has the following script.

<script src="supervisor/lib/jquery-1.6.min.js" type="text/javascript"></script>

Inside jQuery file, I inserted the following code:

$.getScript('functions.js', function () {
  // code here
});

The file functions.js has the following code:

$.getScript('mask.js');
$.getScript('validations.js');
$.getScript('lotsofscripts.js');
// and more...

I want the code here in the first $.getScript() to execute only after ALL the other JS are loaded, but this is not ocurring. What's the best way to achieve this?

PS: I'm using lots of $.getScript() because I find easier to separate them, but I want them to be inserted inside the same file.


Solution

  • You could always just increment a counter. That way your getScript calls remain asynchronous, as the last thing you want to do is change that. And frankly, any packaged solution you find to loading the scripts in parallel and then executing some function afterward will probably just be a shinier version of this:

    var counter = 0;
    var filesToLoad = ["mask.js", "validations.js", "lotsofscripts.js"];
    var filesCount = filesToLoad.length;
    
    // Increment counter each time a getScript completes
    function incrementCounter() {
      if (++counter === filesCount) {
        // This code will execute after everything loads
      }
    }
    
    // Iterate through the files and run getScript on them,
    // with incrementCounter as the callback
    for (var i = 0; i < filesCount; i++) {
      $.getScript(filesToLoad[i], incrementCounter);
    }
    

    Here's a jsFiddle example.