Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browsers react differently to <script> inside <body>

Here is the problem I can't understand. Look at this JS code:

<!DOCTYPE HTML>
<html>

<head>
  <meta charset="utf-8">
</head>

<body>
  <p>The Beginning...</p>
  <script>
    alert('Hello, Wolrd!');
  </script>
  <p>...The End Of Doc</p>
</body>

</html>

So the problem is that I do not understand why The Beginning paragraph isn't loaded/visible before the <script> tag. In almost all tutorials it's explained that the browser loads all HTML before it meets script, then when the script is met the browser starts working in script's compilation mode and then when the script ends browser returns in HTML mode.

But on practic it seems that it behaves differently, as The Beginning text appears only after script alert:

enter image description here

Could please someone explain why is that happening?


PS: Only Firefox behaves as described in the tutorials.

like image 933
Kharlamov Anton Avatar asked Jun 08 '18 09:06

Kharlamov Anton


1 Answers

The elements from before the script have been created and added to the DOM, but the browser hasn't had a chance to render them (update the page display to show them) before the alert brings the whole UI thread to a screeching halt. The browser is required to have created the elements and added them to the DOM; it is not required to have rendered them yet. Some will, some won't. Neither is "wrong."

We can readily prove that the first paragraph exists by looking for it and even reading its text:

<p>The Beginning...</p>
<script>
  alert("Hello, World! First paragraph's text: " + document.querySelector("p").textContent);
</script>
<p>...The End Of Doc</p>
like image 107
T.J. Crowder Avatar answered Nov 20 '22 07:11

T.J. Crowder