Async JS is the way of the present (and future). We MUST load all of our scripts async. They are getting heavy and slow, and the browser needs help, specially on mobile devices. Why wouldn’t you want your page to load faster (see this post).
As web pages grow more and more complex, the idea of a single script that does everything is Jurassic. But what if we want to run code that depends on multiple scripts at the same time? If your app/site is complex you should look into requireJS. If you need something less daunting … I got you (with jQuery):
1 2 3 4 5 6 7 8 9 10 11 12 |
$.when( $.getScript( 'myscript1.js' ), $.getScript( 'myscript2.js' ), $.getScript( 'myscript3.js' ), $.Deferred( function( deferred ) { $( deferred.resolve ); }) ).done( function( script1, script2, script3 ) { // Do whatcha gotta do, all 3 scripts are loaded now } ); |
Neat right? … Let’s kick it up a notch. Say we need the script AND some external data file:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$.when( $.getScript( 'myscript1.js' ), $.getScript( 'myscript2.js' ), $.getScript( 'myscript3.js' ), $.ajax( 'myData.json' ), $.Deferred( function( deferred ) { $( deferred.resolve ); }) ).done( function( script1, script2, script3, myData ) { // Do whatcha gotta do, all 3 scripts and data file are in } ); |
And now the cherry on top … we want to load myData.jsonĀ or yourData.json or just nothing conditionally:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var theCondition = 1; $.when( $.getScript( 'myscript1.js' ), $.getScript( 'myscript2.js' ), $.getScript( 'myscript3.js' ), ( function() { if ( 1 === theCondition ) return $.ajax( 'myData.json' ); if ( 2 === theCondition ) return $.ajax( 'yourData.json' ); } )(), $.Deferred( function( deferred ) { $( deferred.resolve ); }) ).done( function( script1, script2, script3, theData ) { // Do whatcha gotta do, all 3 scripts and data file depends on the theCondition variable } ); |
I’m sure you can do something similar on vanilla JS … but if you need something like this, chances are you are running jQuery.