Synchronous to Asynchronous
A common case is when including a library of functions for use within the current page, as in the following snippet:
It seems sensible to expect that, by the time we get to the call to ‘usefulFn()’, that ‘usefulLib.js’ (including the code for ‘usefulFn()’) would have fully loaded. In fact, it would be a nuisance if we couldn’t rely on this being the case. Imagine if, at the whim of the browser, or other happenstance, it was sometimes the case that ‘usefulFn()’ wasn’t available to call after ‘usefulLib.js’ had been requested for inclusion.
For these cases, the HTML ‘<script>’ element has the ‘defer’ and ‘async’ attributes (the latter introduced in HTML5). In short, ‘defer’ requests that the loading of the specified file occurs after the including page has finished loading, and ‘async’ requests that the loading of the specified files occurs concurrently with (or, at least, independently of) the including page.
These attributes may be used in a similar manner to any HTML attributes, e.g.:
Sync to Async Example Code
var startNow = new Date(); var pauseFor = 5000; // In milliseconds. while (new Date() - startNow < pauseFor) ;
If you browse to this page, you should experience a five-second pause after which the 'Time's up' alert box will pop up. This shows that, by default, the HTML '<script>' tag loads and runs the specified source file to completion before proceeding with rendering/executing the including page.
Now tweak the first of the '<script>' lines above to include the 'async' attribute, like this:
If, after this edit, you refresh the page (and assuming you have a browser that supports HTML5), you should see the 'Time's up' alert pop up immediately, while the 'busy.js' code runs independently.
As we've already established, there are good reasons for generally favouring asynchronous behaviour. Putting the rendering of your web page on hold waiting for some external file to load (which may be on another server on the other side of the world, and which may not even be available at the moment) isn't always the smartest move. Sometimes, however, being able to (for example) load a file synchronously is just what's required.
In this case, I resorted to the use of AJAX to read (and include) the contents of source files synchronously for precisely the same reasons that the HTML '<script>' tag defaults to being synchronous: because I want to be able to rely on included code being available to me immediately after including it.
Here's a synchronous version of the previous example:
A Note About Local Files