Add Async And Defer Attributes to JavaScript Elements
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="http://wpcodesnippet.com/add-async-and-defer-attributes-javascript-elements/scripts.js" async></script>
// defer
<script src="http://wpcodesnippet.com/add-async-and-defer-attributes-javascript-elements/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
async
anddefer
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.
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 defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior 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="async";
}
add_filter( "clean_url', 'wcs_defer_javascripts', 11, 1 );
Share the love
If you like this snippet, share it with others!