Why doesn't parsing HTML stop when I use an inline <script> tag?

Viewed 382

I started to learn web programming for the first...

I learned that The parsing HTML thread is paused when it find <script> tag, and restart after running the script. so I tested it in many ways and found something hard to understand. The first example called case1.html is using an inline script tag. Another one called case2.html is using the external script file(case2.js).

case1.html

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Case 1 Ttitle</title>
  </head>
  <body>
    <p>Before external script</p>
     <script>
        var delay = 5000;
        var start = new Date().getTime();
        while (new Date().getTime() < start + delay);
     </script> 
     <p>after external script</p>
    </body>
</html>

case2.html

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Case 2 Ttitle</title>
  </head>
  <body>
    <p>Before external script</p>
     <script src="./case2.js"></script> 
     <p>after external script</p>
    </body>
</html>

case2.js

var delay = 5000;
var start = new Date().getTime();
while (new Date().getTime() < start + delay);

As I understand it, the two results should be the same, but they were completely different. I tested using the latest version of the chromium browser.

In the case1.html, there was nothing at first and then five seconds later all the text was printed as shown in the right picture.

Using the developer tools, I looked at the execution flow: I don't know why parsing HTML goes on one flow without breaking off and running a script at the same time... and there are two 'paint' sections(green) after a five-second evaluate script. and the script execution and parsing are repeated.

In the 'case2.html', the sentence in front of the script was printed right away, and then another sentence was printed after 5 seconds. There are two parsing sections: one in the front of the evaluating script, and another one in the back.

I know that the parsing HTML thread is paused when it find <script> tag, and restart after running the script. The case 2 makes sense, but I can't understand the result of the case 1...

My Question is, why does parsing HTML continue in case 1 and why does the first print run after the inline script ends?


I've read the following, but I haven't got a clear answer...

Thank you so much for reading my question!

1 Answers

No rendering occurs while running a script.

But rendering is allowed while waiting for a network resource to be fetched. So in case2.html, everything that has been parsed before the <script> tag is rendered while waiting for the script to be fetched. Then it blocks and executes the script.

Related