Many times we may want to load an external script dynamically, using AJAX. If the script is located within a domain different to yours, it must be retrieved asynchronously, which means it will load and execute in the background whilst script execution continues. jQuery has many handy functions we can utilise to make AJAX requests, and most, if not all, allow you to specify a callback function to be executed when the script has loaded, or failed to load. This doesn’t address the point of this post, but it is great, as we can make sure a script has completely finished loading before trying to use it.
But what if we have some code that has multiple external dependencies? Or what if we have multiple external script files which need to load and execute in a specific order? Ideally we would tell jQuery to load the files synchronously, but it’s not allowed. Maybe that’s because it could hang the browser if a request fails.
In comes a method I’d like to call the ‘Sexy Bowers Super Loop’, which despite it’s name, isn’t very funny or sexy. But then again, have you ever met a funny, or sexy, web developer? If so, send them our way, and we can fix the ratio in the office.
The following function will load and then execute the given array of script urls in the order specified within the array. It works by using the magic of recursive looping. Each script is loaded asynchronously, and the function is called again from the AJAX callback in order to load the next script. The function also allows you to pass an optional callback function to be executed once all scripts have finished loading.
*Note: If any of your external scripts do anything asynchronously, such as load in their own external scripts, then this method might not work for you.