How to Add Async And Defer Attributes to JavaScript Elements
One of the suggestion that you always hear about JavaScript elements is to put them very close to the closing tag of the Web page. The main reason for that is that script elements are fetched and executed immediately when the browser encounter them. In most cases, this will improve website speed considerably.
HTML5 introduces the async script attribute which helps to load scripts asynchronous. But older browsers and any version below Internet Explorer 10 does not support async attribute, therefore you can use defer attribute, that is very similar to the async attribute. Here is example usage of each in HTML.
// async
<script src="scripts.js" async></script>
// defer
<script src="scripts.js" defer></script>
So question is which one do you use and what is the main difference between both. Well, this blog post explains the difference between async and defer attributes.
Both
asyncanddeferscripts 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 betweenasyncanddefercenters around when the script is executed. Eachasyncscript executes at the first opportunity after it is finished downloading and before the window’s load event. This means it’s possible (and likely) thatasyncscripts are not executed in the order in which they occur in the page. Thedeferscripts, 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.
It’s very important to remember not to use the defer attribute on external script files that use the document.write or generate document content. But both, async and defer attributes can be used simultaneously on a script element.
“The
deferattribute may be specified even if theasyncattribute is specified, to cause legacy Web browsers that only supportdefer(and notasync) to fall back to thedeferbehavior instead of the synchronous blocking behavior that is the default.”
Here is a code snippet to add the async and defer attributes to all script elements. You can add this snippet to your functions.php file.
// add async and defer to javascripts
function wcs_defer_javascripts ( $url ) {
if ( FALSE === strpos( $url, '.js' ) ) return $url;
if ( strpos( $url, 'jquery.js' ) ) return $url;
return "$url' async onload='myinit()";
}
add_filter( 'clean_url', 'wcs_defer_javascripts', 11, 1 );

Leave a Reply