Can you use both the async and defer attributes on a HTML script tag?
From the specification: https://www.w3.org/TR/2011/WD-html5-20110525/scripting-1.html#attr-script-async
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.
The question is, what would you expect it to do? If both async and defer are present I would expect the script to be deferred and only executed after DOMContentLoaded when the browser is idle, but if I'm reading the specification right it looks like defer is ignored if async is set and the script is loaded asynchronously, so will execute as soon as it's available, which may well be before DOMContentLoaded and may block other resources.
There are three possible modes that can be selected using these attributes. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.
https://www.w3.org/TR/2011/WD-html5-20110525/scripting-1.html#attr-script-async
Unfortunately defer
is ignored when async
specified, and async
always have higher priority. (At least in Chrome. Honestly, did not tested in other browsers, but I think that result will be the same.)
And personally I think that it's very bad that defer
is ignored. Let's imagine situation when we would like to have some JS initialized ASAP, even before loading of the page content. But we want this script initialized BEFORE the rest of scripts which requires it. It should be first in defer
queue. But, unfortunately, this will not work:
<!-- we want "jQuery" ASAP and still in "defer" queue. But defer is ignored. -->
<script src="jquery.min.js" async defer></script>
<!-- this doesn't blocks the content and can wait the full page load, but requires "jQuery" -->
<script src="some_jquery_plugin.min.js" defer></script>
In this sample the "some_jquery_plugin.min.js" can be loaded and executed before the load of jQuery, and will fail. :(
So there is 2 ways to solve the problem: either use only defer
directive, or merge all depending javascript files into single JS.