Why does the alert prevent HTML from being displayed when the page is loading?

Asked

Viewed 31 times

2

Can someone explain to me why the <h1> and the <p> only appear after closing the alert box?

<body>
   <h1>Meu primeiro programa em JS</h1>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Maiores quia culpa nesciunt earum! Placeat, natus.</p>

   <script>
      window.alert('Meu primeiro programa em JS');
   </script>
 </body>

1 answer

2

In fact the HTML of <h1> and <p> are loaded before the <script>. However, the <script> in this case it was executed before the HTML was "painted" on the page, and as the alert is synchronous, it prevents the elements from appearing until it is closed, also preventing any other interaction on the page.

You can see that if we delay the alert, the page is not empty:

// O mínimo tempo (1ms) já é capaz de reverter esse comportamento.
//                         ↓
setTimeout(() => alert(1), 1);
<h1>Lorem Ipsum</h1>

But if the alert run immediately, we have what you showed us:

alert(1);
<h1>Lorem Ipsum</h1>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.