Once upon a time, there were many heated debate on <script>
in <head>
or <body>
.
Many SO posts had already pointed out the best practice / rule of thumb is to place the <script>
before end of <body>
for not blocking the html parser, resulting faster first screen paint and quicker DOM access for client, and thus a better UX.
This must be a duplicate╰(‵□′)╯
Wait ... <script>
can be deferred
now, actually for quite a while !
Old posts said
deferred script may results JS dependency issues
No, it won't. It retains the order on execution immediately when the DOM gets parsed.
It doesn't work cross vendors
Yes, it once was, but today it's almost supported by all major browser vendors: http://caniuse.com/#search=defer, besides may have some problem with IE<10 as the comments point out.
However, the benefits it offers seem obvious, at least to me, as it downloads the script in parallel at earlier time(before start parsing the DOM), thus no need to request the script later and shortens the time it takes to bring the whole page interactive.
To be short, this question is similar to: Any good reason not to use
<head>
...
<script src='cdn/to/jquery' defer>
<script src='cdn/to/bootstrap' defer>
<script src='script/depends/on/jqueryandbootstrap' defer>
</head>
instead using this:
<body>
...
<script src='cdn/to/jquery'>
<script src='cdn/to/bootstrap'>
<script src='script/depends/on/jqueryandbootstrap'>
</body>
note: This might be an "ancient" topic with lots of discussions. However, as web technology moves really fast, browser vendors align better and more consistent with new web specs, many old stackoverflow answers may not keep up-to-date.
defer
now :p – Overviewasync
anddefer
should take less time in total. – Pulsarasync
is the one that can cause dependency issues. You can use defer, if the browser doesn't support it, it may take a little longer to load but it won't break the page. – Gaelandefer
, the fallback will be the same as putscript
before end ofbody
. – Pulsarhead
withoutdefer
– Gaelanscript
before end ofbody
, i'm trying to figure out why here. One of the main reason it gives is the old browser problems which i've already pointed out in the post. – Pulsardefer
) magic attribute; This is an interesting article I found on Mozilla Hack – Weevilydefer
remove the need for $(document).ready()? – Abstract