Load Cross-Domain Javascript Synchronously Using jQuery

When you use a script tag to include Javascript in an HTML document, it’s content is loaded synchronously. This means that the whole script is loaded and executed before the browser continues to process the page. This is very useful, as it means we can load a large script, such as jQuery, and then use it in any subsequent Javascript. Of course, we can’t do anything that amends the DOM until the whole page has loaded, but we can access any variables that the jQuery script sets up, such as it’s global dollar: ‘$’.

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: