skip to Main Content

in the below codes:

<!DOCTYPE html>
<html>
  <head>
    <title>Hello World</title>
  </head>
  <body>
    
    <span>1111</span>
    
    <script>
      alert("1");
    </script>
    
    <span>22222</span>
    
    <script>
      alert("2");
    </script>
    
      <span>Hello World</span>
     <script>
       alert("Hello World");
     </script>
      
  </body>
</html>

In the body tag there are some span tags that after each one there are one script tag. in the each script tag just an alert there is.

When I open these codes by a browser, I expect that span tags executed(rendered) before than alerts. because spans are before than alerts (alerts are after than spans!)

But In the real test, it is not as I expected (first alerts shown and then spans will appear.)
Why?!

2

Answers


  1. When a page loads, the browser starts displaying and processing it as the code is received and processed. In this case, when the browser encounters the tag, it executes its contents, and then continues displaying the page.

    To change this behavior, you can use special attributes, for example defer.

    Login or Signup to reply.
  2. When loading a page a browser will render and "paint" the page until it encounters a blocking resource. Synchronous javascript is render blocking. Alert in this case is being called synchronously and prevents the page from rendering.

    When running your code, my browser is blocked by the first two alerts but has parsed enough HTML to render the "1111" and "22222" elements before being blocked again by the third alert, "hello world".

    Here’s some related reading:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search