Nika Kurashvili
Nika Kurashvili

Reputation: 6472

JavaScript doesn't block DOM constructing

I have this html:

<head>
</head>
<body>
    <h1>TEST</h1>

    <script src="index.js" type="text/javascript"></script>

</body>
</html>

I specifically made index.js as a big file such as 1MB. and testing this on slow network of google chrome.

Now, the thing is when I run the website, TEST immediatelly appears on the screen. page still is loading(as js file is big), but TEST appears immediatelly.

I've read somewhere that: The entire DOM CONSTRUCTION process is halted until the script finishes executing. If that's the case, why does 'TEST' appear on the screen? DOM construction is not finished because browser encountered the script and how does it know that DOM is ready after it encountered <h1>TEST</h1>.

In my opinion: TEST should be appearing after the index.js has been loaded.

Upvotes: 1

Views: 244

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370989

Only future DOM construction halts when a script is being downloaded/parsed. DOM elements which have already been parsed (such as your <h1>), which come before the script tag, remain in the DOM - the downloading of a script does not result in them being removed until the script is finished.

If you had switched it around:

<head>
</head>
<body>
    <script src="index.js" type="text/javascript"></script>
    <h1>TEST</h1>
</body>
</html>

it would take a bit of time for TEST to be displayed, as you're expecting, because here, the <script> comes before the TEST, so the script needs to be parsed before the TEST appears.

Upvotes: 4

Related Questions