Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<script defer> and $(document).ready

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?

like image 811
Uyghur Lives Matter Avatar asked Dec 26 '11 19:12

Uyghur Lives Matter


People also ask

What does $( document .ready mean in JavaScript?

$( 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.

What is script defer?

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.

What does this do $( document .ready function ()?

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.

Should I use defer in script tag?

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.


1 Answers

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/

like image 128
Telmo Marques Avatar answered Sep 27 '22 20:09

Telmo Marques