According to http://caniuse.com/script-defer, most browsers support the script
tag's defer
attribute.
I would like to know if scripts specified by <script defer src="...">
get executed before or after jQuery's $(document).ready()
? Are the major, modern browsers (Chrome, Firefox, IE, etc.) consistent in the order of execution or does it vary?
$( document ). ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
defer. This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded . Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating.
The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.
Defer attribute is useful when script is using for DOM manipulations. Means script will apply on document html. async attribute: It will download the script file and execute without wait the end of html parsing. In other words, It will not guarantee all the scripts will execute after the html parsing.
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/
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