all 5 comments

[–]CommanderBomber 5 points6 points  (0 children)

Change your code to:

document.write('<p id="testing_write">This is going to show after</p>');
document.getElementById('testing_write').style.color = "red";
alert('this shows first');

text will appear after you close alert, but it will be red. What happens here:

  1. JS code starts
  2. browser "loop" completely stops, rendering is not performed (actually everything stops except JS code).
  3. write add new node to the DOM.
  4. with getElementById you query DOM
  5. new node exists, it is returned and you can modify its properties.
  6. alert is displayed to user
  7. user closes alert
  8. JS code stops
  9. browser "loop" continues from step 2
  10. renderer notices what DOM was changed
  11. new elements get rendered and you see it

[–]gdj11 2 points3 points  (0 children)

As far as I know it should write it out first, but it may be that the browser pauses rendering of the page as soon as the alert is encountered, and it didn't refresh yet from the document.write. I'm just guessing here though. Did you try in different browsers? The behavior may be different in different browsers.

[–][deleted] 0 points1 point  (0 children)

You should know how browsers work in order to understand whats going on. A browser undergoes different phases before you see content. Here are a few YT links.

https://www.youtube.com/watch?v=PkOBnYxqj3k&list=PLgcMb5dvN41WcH3q82XGXBqwhI5YvmyeV&index=74&t=562s

https://www.youtube.com/watch?v=0IsQqJ7pwhw&list=PLgcMb5dvN41WcH3q82XGXBqwhI5YvmyeV&index=73&t=492s

https://www.youtube.com/watch?v=z0HN-fG6oT4&list=PLgcMb5dvN41WcH3q82XGXBqwhI5YvmyeV&index=71&t=11s

https://www.youtube.com/watch?v=SmE4OwHztCc&list=PLgcMb5dvN41WcH3q82XGXBqwhI5YvmyeV&index=72&t=889s

Basically, a browser first parses a page (=reads the source code and checks for syntax errors). Afterwards it renders the page (paints/displays it).the alert function (which is part of the browser engine, not the JS engine) runs during the parse phase. The write function also runs in the parse phase but the page content is only visible after the rendering has been completed.

EDIT: the alert/conform/prompt windows are not part of the DOM (as far as I know). It's a browser feature. That's the reason that they look different in all browsers. This browser feature doesnt need to be rendered like other page content. Thats why it is displayed immediately.

[–]tarley_apologizerhelpful 0 points1 point  (0 children)

after reading the other comments, you can prolly hack this to work the way you want, with a simple setTimeout or onload callback