JavaScript JavaScript Basics (Retired) Introducing JavaScript Your First JavaScript Program

Angelique Sipos
Angelique Sipos
Front End Web Development Techdegree Student 984 Points

JS out of order in Chrome?

Hi, I'm noticing that the JS seems to be happening out of order while using Chrome.

alert("Hello from Treehouse"); document.write("<h1>Welcome to JavaScript Basics</h1>"); alert("Thanks for visiting.");

That is my code. After refreshing, I get alerted the first time, then when I click OK, the alert with "Thanks for visiting" opens up. When I click OK then, the document.write statement gets printed on the page afterward. I'm not sure why the script seems to be running out of order.

When I view this on Firefox, each step happens accordingly. Why do you think this is happening?

2 Answers

Liam Clarke
MOD
Liam Clarke
Treehouse Moderator 19,722 Points

Hello

Chrome is actually doing them all in order however the actual rendering on the document write is happening after.

The reason it does this is the JS engine that each browser uses is slightly different, hence why you have different support for different versions.

In the case of the alert, it’s generally considered bad practice as it is classed as a legacy event, blocking the event loop which as you have found out is pretty unreliable.

As for what’s going on behind the scenes though, your code is actually running line by line, however rendering takes place after hoisting and after an event is fired, making your document.write get called before but not rendered until the next loop.

Probably one of the best talks I’ve seen about JS event loop which will explain everything your seeing here

Angelique Sipos
Angelique Sipos
Front End Web Development Techdegree Student 984 Points

This makes more sense now, and I'll definitely watch the JS event loop video. Thanks for sharing!

Nicole Antonino
Nicole Antonino
12,259 Points

This could be because the alert() method is actually controlled by the browser software rather than the JavaScript itself and therefore the 2 browsers may have different ways of implementing it.

Angelique Sipos
Angelique Sipos
Front End Web Development Techdegree Student 984 Points

Thank you for your reply. Years ago I remember wrestling with creating websites that were cross-browser compatible. It was always disheartening to see one's web design botched up in one browser while looking stellar in another. I had little idea that this would happen with programming as well, but why wouldn't it, right? Now I'll be more aware, though I don't think it'll be less frustrating! :)