WebKit Native Asynchronous Script Loading

Avatar of Chris Coyier
Chris Coyier on

WebKit nightlies are now supporting this. The syntax looks like this:

<script async src="myAsyncScript.js" onload="myInit()"></script>
<script defer src="myDeferScript.js" onload="myInit()"></script>

Both async and defer scripts begin to download immediately without pausing the parser and both support an optional onload handler to address the common need to perform initialization which depends on the script. The difference between async and defer centers around when the script is executed. Each async script executes at the first opportunity after it is finished downloading and before the window’s load event. This means it’s possible (and likely) that async scripts are not executed in the order in which they occur in the page. The defer scripts, on the other hand, are guaranteed to be executed in the order they occur in the page. That execution starts after parsing is completely finished, but before the document’s DOMContentLoaded event.

In the past this was done with the clever technique of creating new script element in JavaScript and appending it to the head after the page was loaded. This is easier and cleaner. Let’s hope other browser makers pick it up as well, and with the same syntax.

Direct Link →