0

Is always the code written at the bottom of the doc executed after the DOM ready ?

Is listening to the ready event of the document

<!DOCTYPE html>
<html>
<head>
    <script src="js/jquery.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function() {
            // code ..
        });

    </script>

</head>
<body>

    <!-- Document -->

</body>
</html>

Equivalent to writing the code at the bottom of the document ?

<!DOCTYPE html>
<html>
<head>
    <script src="js/jquery.js" type="text/javascript"></script>
</head>
<body>

    <!-- Document -->

    <script type="text/javascript">

        // code ..

    </script>
</body>
</html>
faressoft
  • 19,053
  • 44
  • 104
  • 146
  • http://stackoverflow.com/questions/6026645/document-readyfunction-vs-script-at-the-bottom-of-page – j08691 Feb 27 '15 at 01:36

3 Answers3

3

Practically, they're close enough that the behavior will be the same for a lot of scripts. Regarding the "code at the bottom of the document" case:

The entire document will have been parsed, except for the end tags. But the way the tree construction algorithm works, the transitions (1, 2) caused by </body> and </html> (provided that your markup is fairly sane) don't affect the tree.

Strictly speaking, code in a <script> tag at the bottom without async or defer attributes executes before the DOMContentLoaded event, so a DOMContentLoaded event handler would still run if registered there. But jQuery's $(document).ready() will run the provided callback immediately if DOMContentLoaded has already been dispatched.

They're drastically different if you want to use document.write though.

guest
  • 6,450
  • 30
  • 44
0

script in body(in between markup) will be executed when DOM is loading . whereas script in the end of document and document ready will be executed when dom is loaded.

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

While the DOM won't technically be ready until after it's parsed the whole document, the practical result would be the same. All the HTML elements on the page will have been loaded, and your script will be able to interact with them, just as if you had waited until the dom was ready. That being said, waiting until the DOM is ready is often unnecessary and may make your application slower than it needs to be.