The question is about the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
</head>
<body>
One line of HTML code
<script>
// Synchronous delay of 5 seconds
var timeWhile = new Date().getTime();
while( new Date().getTime() - timeWhile < 5000 );
</script>
</body>
I tested it in Firefox and Chrome and they are showing (rendering): "One line of HTML code" after 5 seconds and not within 5 seconds. Why is a browser doing that?
I understand why a browser has to stop rendering when executing JavaScript, because you can change the style of elements with JavaScript (as an example). It would give problems if the browser has to show and change content exactly at the same moment. That's why a browser is blocking rendering while executing JavaScript.
In the example above when starting with the executing of JavaScript, "One line of HTML code" is already parsed by the "HTML parser". It has to, because JavaScript can contain for example document.write, so then the appended string has to come after the preceding HTML. Apparently there is some time between "parsing HTML" and showing / rendering that same HTML, because otherwise the browser in this example would already show something within 5 seconds, but that's not the case.
When you replace "One line of HTML code" by a lot of HTML code then the browser will already show some content within the 5 seconds, so in principle it's possible to show already some content.
If I would be a browser then I would do:
- Parse "One line of html code"
- Seeing some block of JavaScript
- Finish rendering the HTML, preceding the "JavaScript block", so the browser will show at this point: "One line of HTML code"
- Now pause rendering and execute the JavaScript code.
- After executing the JavaScript code, start rendering again.
In an example like this, the browser could show some content 5 seconds earlier. That's a big speed gain in terms of rendering.
Maybe it's something that browsers can improve, but maybe there is another reason. Maybe someone knows more about it and can explain me that.