According to http://caniuse.com/script-defer, most browsers support the script
tag\'s defer
attribute.
I would like to know if scripts spec
The defer attribute has a good write-up and analysis. Also See the comments to the post for additional info on how defer
has been re-defined in HTML5.
My conclusion: defer
is too browser dependent to count on. Therefore use the jQuery doc ready technique.
To put it another way, an important reason for jQuery is to cover browser inconsistencies. Defer is another such inconsistency that should be avoided for well written pages.
To defer inline javscript you can use type="module" which then makes $(document).ready() redundant.
<script type="module">alert('defered inline js')</script>
Because type="module" implies defer scripts will execute in order with other deferred scripts.
See can I use 92% browser support in September 2020. https://caniuse.com/es6-module
Simply, script
should be executed before $(document).ready()
whether defer
is used or not and almost all major browsers support defer
.
But for being safe side I encourage you to use both $(document).ready()
and defer
.
So why defer
? Because it helps page appear quickly (as external script is loaded parallel) and a really important factor in Google's page speed tool, a good detail can be found here http://code.google.com/speed/page-speed/docs/payload.html#DeferLoadingJS
Based on this fiddle I have to say jQuery's $(document).ready()
executes after a script declared with defer
. I tested it with Firefox and Chrome, and both had the same behavior independently of the sequence of the scripts.
I guess behavior on other browsers might change based on their implementation, so it's always uncertain.
EDIT: As it turns out, the defer
attribute should be used with an external javascript file. I edited the fiddle to show this, apparently with the same results.
Updated fiddle here: http://jsfiddle.net/RNEZH/15/