4

When the following code, in the order written, is executed, why does the alert still come first even though it's on the 2nd line? Thanks!

document.write ("Hello World");
alert("You wrote to the document!");
Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
servo
  • 55
  • 6
  • 2
    the buildup of the document takes longer than the "parsing" of the file , thats why the alert is executed before the page is built. You need to wait until the document is ready. see [javascript-that-executes-after-page-load](https://stackoverflow.com/questions/807878/javascript-that-executes-after-page-load) – Patrick Artner Nov 12 '17 at 16:05
  • I don't see how the "similar" question addresses the problem. This seems more relevant: [Why does alert appear before background changes?](https://stackoverflow.com/questions/40945552/why-does-alert-appear-before-background-changes) – showdev Mar 26 '22 at 23:37

2 Answers2

2

Javascript is interpreted so it goes line by line so the document.write is running first and alert is running after it.Moreover, in single threaded javascript model the further execution is stopped till the response of popups are received.

The reason why you don't see the result is that the rendering of HTML is stopped due to alert popup so all the popups will be seen before most of the rendering of your page. This link will help you understand better.

Black Mamba
  • 13,632
  • 6
  • 82
  • 105
1

Modern browsers are set up such that once they encounter a JavaScript code they will essentially pause the rendering of HTML and run though the entire JavaScript before they resume the HTML rendering.

Mamun
  • 66,969
  • 9
  • 47
  • 59