Is inline/block Javascript executed before document-ready?

Jérôme Verstrynge picture Jérôme Verstrynge · May 18, 2013 · Viewed 8.9k times · Source

Assuming one has inline Javascript code in a HTML document (the body for example), is this piece of Javascript always executed before JQuery document-ready code?

For example, is the following safe?

...
<body>
    <script type="text/javascript">
        var myVar = 2;
   </script>
   ...
</body>

...
$(document).ready(function() {
    alert('My Var = ' + myVar);
}

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

Answer

nnnnnn picture nnnnnn · May 18, 2013

Yes, the above code is safe. Inline JS is executed as it is encountered while the document is being parsed top to bottom. The document ready handler is executed when the document is ready (obviously), and it won't be ready until the whole document has been parsed including inline scripts.

Note that you don't really need a document ready handler if you include the code that it wraps as the last thing in the document body, because at that point not only will other inline JS have executed but all of the document elements will have been added to the DOM and thus be accessible from JS.