To imitate render blocking and why this attempt has not succeed?

30 views Asked by At
<!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.

enter image description here

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.

enter image description here

What has happened here? And how can I imitate render blocking?

1

There are 1 answers

0
Rick Viscomi On

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:

Performance panel screenshot of a very quick task

To intentionally block the main thread (just for demonstration purposes) you can use a while loop that continuously executes until the time is up:

function delay(ms) {
  const startTime = new Date();
  while (new Date() - startTime <= ms);
}
const yourFunction = () => {
  delay(5000);
  console.log("Waited 5s");

  delay(5000);
  console.log("Waited an additional 5s");
};
yourFunction();

In this performance trace you can clearly see that the main thread is completely blocked for 10 seconds:

Performance panel screenshot of a 10 second task

And the console shows the logs in the order they appear in the code:

Console logs: Waited 5s, waited additional 5s, loaded