0

I'm attempting to familiarise myself with JavaScript and how it interacts with webpages, and so I mocked up a little something below:

<!DOCTYPE html>
<html>
  <head>
   <meta charset="utf-8">
   <title>Example Page</title>
  </head>
  <body>
    <p>This is paragraph 1</p>
    <script>
      alert("First Script Block")
    </script>

    <p>This is paragraph 2</p>
    <script>
      alert("Second Script Block")
    </script>

    <p>This is paragraph 3</p>
    <script>
      alert("Third Script Block")
    </script>
  </body>
</html>

CodePen

The HTML source defined above contains multiple script tags which display simple alerts. From my understanding HTML is parsed in a top-down fashion, so each script element should be hit after its associated paragraph element. But this does not seem to be the case, instead the script which triggers the alert seems to be encountered before the paragraph content on the page has updated, i.e. I receive the "First Script Block" alert before "This is paragraph 1" is displayed on the page. The intended behaviour I had in mind was for "This is paragraph 1" to be displayed first, and then for the alert "First Script Block" to pop-up.

Could someone explain the shortcoming in my understanding here?

seeker
  • 530
  • 1
  • 4
  • 14
  • The page hasn't had a chance to render yet, at the point that the script tags are seen - but `alert` completely prevents Javascript execution *and* page parsing *and* page rendering. (Best to never use `alert`) – CertainPerformance Feb 09 '20 at 05:22
  • @CertainPerformance even if the script comes after the content in question? Why doesn’t “This is paragraph 1” at least load before the first alert? The paragraph element is encountered first after all? – seeker Feb 09 '20 at 05:25
  • 1
    Yes - even if the script runs after the other element in the DOM, the script will run before the browser has had a chance to paint the page. The browser will only start painting once resources are free *and* no alert-like boxes are active. Up until the script block, the browser has been completely focused on parsing the HTML into the DOM. Then when the script is encountered, an alert box comes up, preventing the browser from painting. – CertainPerformance Feb 09 '20 at 05:28

0 Answers0