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.
Yes, but only because you're using jQuery.
jQuery doesn't work with defer
because it tries to fire as soon as the page becomes interactive. They can't fix it any time soon (I raised that bug over a year ago) because changing the ready behaviour to work with defer
will break lots of components that rely on jQuery's ready event firing on interactive (i.e. before deferred scripts have finished loading).
If you're using a more modern framework (React, Angular 2, Polymer, Vue, or just about anything else) then go for it - or even go to the next step and use <script type=module
in new browsers and a legacy bundle in <script nomodule defer...
for IE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With