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.
- case 1 result screenshot
(I'm sorry I can't post images... I used links)
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...
- Render blocking Javascript at end of body tag - Firefox renders some visual content, Chrome does not
- Why do inline scripts block rendering when put at the bottom of a page?
- https://developers.google.com/web/tools/lighthouse/audits/blocking-resources
Thank you so much for reading my question!