The real answer is: Because you cannot trust defer.
In concept, defer and async differ as follows:
async allows the script to be downloaded in the background without blocking. Then, the moment it finishes downloading, rendering is blocked and that script executes. Render resumes when the script has executed.
defer does the same thing, except claims to guarantee that scripts execute in the order they were specified on the page, and that they will be executed after the document has finished parsing. So, some scripts may finish downloading then sit and wait for scripts that downloaded later but appeared before them.
Unfortunately, due to what is really a standards cat fight, defer's definition varies spec to spec, and even in the most recent specs doesn't offer a useful guarantee. As answers here and this issue demonstrate, browsers implement defer differently:
- In certain situations some browsers have a bug that causes
defer
scripts to run out of order.
- Some browsers delay the
DOMContentLoaded
event until after the defer
scripts have loaded, and some don't.
- Some browsers obey
defer
on <script>
elements with inline code and without a src
attribute, and some ignore it.
Fortunately the spec does at least specify that async overrides defer. So you can treat all scripts as async and get a wide swath of browser support like so:
<script defer async src="..."></script>
98% of browsers in use worldwide and 99% in the US will avoid blocking with this approach.
(If you need to wait until the document has finished parsing, listen to the event DOMContentLoaded
event or use jQuery's handy .ready()
function. You'd want to do this anyway to fall back gracefully on browsers that don't implement defer
at all.)
defer
is only valid when specifyingsrc
. This might be a reason why your example did not work as expected in most browsers. – Hahnke