Is the inline / Javascript block executed until ready for the document?

Assuming one has embedded Javascript code in an HTML document (such as a body), does this piece of Javascript always execute before the code of the finished jQuery document?

For example, is it safe?

... <body> <script type="text/javascript"> var myVar = 2; </script> ... </body> ... $(document).ready(function() { alert('My Var = ' + myVar); } 

If not, how can I make this safe, knowing that myVar is defined in inline / block code?

+8
javascript jquery html document-ready
source share
3 answers

Yes, the code above is safe. Inline JS is executed as it occurs when a document is parsed from top to bottom. The document handler is ready when the document is ready (obviously), and it will not be ready until the entire document has been analyzed, including built-in scripts.

Note that you really do not need a document handler if you include the code that it wraps as the last thing in the body of the document, because at that time only other built-in JS will not be executed, but all elements of the document will be added to the DOM and therefore will be available from JS.

+10
source share

Yes, inline JavaScript runs during HTML parsing.

This is safe if you are not trying to get a reference to a DOM element that has not yet been parsed (i.e., any element after the script block in the HTML HTML). You can also refer to any variable defined on early script blocks (if there are any in the scope).

And, as Matt Brown noted in his comment, it is generally not recommended to use the DOMContentLoaded listener (either the oldIE or window.onload workaround) if you place your script that relies on the DOM loaded correctly before the closing </body> . At this point, all HTML elements will be in the DOM already (if you do not have additional elements after </body> , which would be incorrect HTML).

+7
source share

We can safely assume that myVAr is available from $(document).ready(function() {}) .

If you run the code in your HTML, myVAr will become a property of the global window JS object (i.e. window.myVar ). I don't think it needs to be created locally in the jQuery function.

+1
source share

All Articles