9

In Chrome, the following code does not display the <h1>Hello</h1> until after the alert is shown and the user clicks ok. However, in Firefox the expected sequence happens, <h1>Hello</h1> is displayed and then the alert appears.

<h1>Hello</h1>
<script>
  alert('Hello is displayed after this alert')
</script>

I'm curious why Hello shows up after the alert is closed in Chrome. Is that what's supposed to happen? Is the HTML/JavaScript spec simply unclear and Chrome just never bothered to make this intuitive? Is it a bug in Chrome?

Sebastian Speitel
  • 6,351
  • 2
  • 16
  • 34
at.
  • 45,606
  • 92
  • 271
  • 433
  • Weird, just tried this out. I think it's because you're script is running before the page is fully loaded. If you put $(document).ready after it 'hello' comes first. First time I've encountered this :D – Sylent Apr 04 '18 at 08:18
  • The elements existing on the page and being part of the DOM is independent of them being _painted_ on the screen. And painting isn’t required to be synchronous. – Sebastian Simon Apr 04 '18 at 08:19
  • See the answer here: https://stackoverflow.com/questions/8996852/load-and-execute-order-of-scripts – Ghazni Apr 04 '18 at 08:22
  • Possible duplicate of [Webpage not loading in chrome while alert is up](https://stackoverflow.com/questions/49317286/webpage-not-loading-in-chrome-while-alert-is-up) – Sebastian Simon Apr 04 '18 at 08:22

2 Answers2

1

The browser has a single thread for rendering HTML + CSS and JavaScript execution. As long as alert is a synchronous call, it blocks this thread.

Looks like Firefox interprets the alert call to be happening after initial rendering (in fact it does not execute this script but pushes it to the event loop) while Chrome executes JavaScript within the rendering process. This could make sense if you use document.write in your script, this is kinda smoothly adding the new items to the DOM before rendering it as a whole.

As a result I would say it is an improvement because the rendering is skipped until you decide what to show; plus it is not anyhow critical - normally you should never use a blocking thread operator while loading the page.

smnbbrv
  • 19,108
  • 9
  • 62
  • 100
0

I belive the problem is that JavaScript and the rendering process share the same thread and calling alert() doesn't only show the popup, but also pauses the mainthread, which prevents the rendering from continuing.

To prevent this problem you just have to let the rendering happen before you call alert() you can do this by adding it to a timout:

<h1>Hello</h1>
<script>
  setTimeout(()=>alert('Hello is displayed before this alert'),1);
</script>

I also tried using the load eventListener and deferring the <script> tag but both didn't work.

Sebastian Speitel
  • 6,351
  • 2
  • 16
  • 34