<!DOCTYPE html>
<html>
<head>
<script>
const delay = ms => new Promise(res => setTimeout(res, ms));
const yourFunction = async () => {
await delay(5000);
console.log("Waited 5s");
await delay(5000);
console.log("Waited an additional 5s");
};
yourFunction();
</script>
</head>
<body>
<p> Hello </p>
<script>
window.onload = function () {
console.log('Loaded');
}
</script>
</body>
</html>
I'm studying phenomena blocking rendering or parsing of HTML.
This is a script in the head. As far as I understand, it should have blocked the rendering. But we can see that the text has been rendered.
And much later 5 seconds expires.
What has happened here? And how can I imitate render blocking?
The Promise/setTimeout actually yields to the main thread, so the browser will continue rendering the page. It's only until the timeout fires that the task resumes execution.
You can barely see the tasks on the "Main" track of the Chrome DevTools Performance panel at the 5 and 10 second marks. Other than those brief moments, there's nothing happening on the main thread, confirming that rendering isn't actually blocked:
To intentionally block the main thread (just for demonstration purposes) you can use a
while
loop that continuously executes until the time is up:In this performance trace you can clearly see that the main thread is completely blocked for 10 seconds:
And the console shows the logs in the order they appear in the code: