JTech Communications

Safely Using Async Javascript

by Patrick Milvich - September 8, 2014
Web Development
In the last article I wrote about asynchronous JavaScript in our web development process, I outlined advantages of loading external scripts in parallel rather than blocking the browser’s rendering of a website.

However: There are website performance problems that can arise if async is used carelessly. In a non-async scenario (where scripts are loaded sequentially), you can guarantee that functions will be available when you want to call them. If, instead, your scripts are loaded asynchronously, there’s no certainty that a given function will be available to run — which can produce errors.

Example:
<script src=“main.js” async></script>
<script>
callFuncInAsyncScript();
</script>
ReferenceError: Can't find variable: callFuncInAsyncScript

We use a simple approach to resolve this timing issue in the JavaScript component of our framework. First, we define an array inline to queue actions. When the asynchronous JavaScript (shown below) loads, it will then process any actions in the queue.

This works by utilizing the behavior of arrays. Instead of executing code directly, we wrap the code in a function that is then pushed on to the array. Then the async code iterates through all all the functions in the array and executes them. Once the queued up functions have executed, we replace the array with an object that contains a push function — which ensures that future pushes to what was once the array will instead execute the function immediately.

The example below sets up our array and pushes functions into the queue array:
<html>
<head>
<script>
var jt = [];
</script>
<script src=“main.js” async></script>
</head>
<body>

<script>
jt.push(function() { callFuncInAsyncScript(); });
</script>

</body>
</html>


Inside the async script (main.js shown above) at the end of the script, we run each of the queued functions in the array, then replace the array:
if(jt) {
jt.forEach(function(func) {
func();
});
}
jt = { push: function(func) { func(); } }

We’ve been happy with this programming approach to safely using asynchronous JavaScript, but I’m always looking for ways to improve our website development process. If you have suggestions to refine how we handle async JavaScript, I’d be very interested in your thoughts.

Monthly inbox insights.

Our articles are published for free on our blog.
 
First Name
 
Last Name
 
Email Address
Subscribe