Monday, 1 October 2018

Why console.log gets executed before DOM model being generated?

In the code below, why does the loop of console.log finish before any HTML element is displayed? I have placed the JavaScript code at the end of HTML file.

<!DOCTYPE html>
<html lang="en">

<body>

    <p id="counter"> no clicks yet </p>
    <script>
        for (i = 0; i < 99999; ++i) {
            console.log(i);
        }
        console.log("ready to react to your clicks");
    </script>
</body>

</html>

Update:

based on one answer I tried this and still HTML doc gets displayed only after console log loop is fully executed:

<html lang="en">

<body onload="onLoad()">
    <button onclick="clickHandler()">Click me</button>
    <p id="counter"> no clicks yet </p>
    <script>
        var counter = 0;
        function clickHandler() {
            counter++;
            document.getElementById("counter").innerHTML = "number of clicks:" + counter;
        }
        function onLoad() {
            for (i = 0; i < 99999; ++i) {
                console.log(i);
            }
            console.log("ready to react to your clicks");
        }

    </script>
</body>

</html>



from Why console.log gets executed before DOM model being generated?

No comments:

Post a Comment