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.

Continue reading “Load Cross-Domain Javascript Synchronously Using jQuery”

Create a website or blog at WordPress.com

Up ↑