Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

Load JavaScript Files Asynchronously

2 min read

I recently worked on a component for our single-sign-on system. As part of that work I also developed a small JavaScript file that was included in the top-header of the page for rendering the username, last access and session expiration or alternatively the login link in case the user wasn't logged on.

The different pages included the JavaScript in their HTML just normally, such as
<script type="text/javascript" src="./..."></script>
<div id="header">
<script type="text/javascript" src="https://authserver.com/AuthenticationHeaderScript"></script>
The included script directly rendered the html in the place where it was included. The problem with this is how the browser loads such scripts: "synchronously".  Basically when it encounters a <script> tag it loads it and waits for its content to arrive. To cap it all, we had some issues with the server that provided that authentication script I mentioned above. What happened was that all pages remained basically blank, because they hung at trying to load that JavaScript.

To overcome this, we took the approach to load the script "asynchronously". jQuery provides a nice function for doing that. $.getScript("...") allows to
Load a JavaScript file from the server using a GET HTTP request, then execute it.
jQuery: http://api.jquery.com/jQuery.getScript/
By wrapping this call in the jQuery ready() function, one postpones the loading of the script till the very end of the page construction which is much better for the user experience as he sees the page content more quickly. To improve this even more, one could introduce a timeout for loading the script. If it doesn't load within 20 seconds, the request could be aborted. This is done by calling the abort() function on the ajax request.
//store the request in a variable
var ajaxRequest = $.getScript("http://somelocation.com/myscript.js");
//to abort
The final result looks something like this:
<script type="text/javascript">
var timeoutLength = 20000;
var timer;
var ajaxRequest;
$(document).ready(function() {
isRunning = true;
timer = setTimeout(function() {
if (ajaxRequest) {
}, timeoutLength);
ajaxRequest = $.getScript("http://authserver.com/AuthenticationScript.js", function() {
Line 7 shows the initialization of the timer by initializing a timeout function. In the callback, the ajax request is being aborted. In line 13 the invocation of the ajax request is demonstrated and subsequently the implementation of the success callback is shown in line 14.
Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus