So what exactly is the order of operations on a page load?

fuzzybabybunny

Moderator<br>Digital & Video Cameras
Moderator
Jan 2, 2006
10,455
35
91
I really want to iron out *exactly* what happens when a browser loads a page. Please correct anything that is wrong.

Say that it's just a normal .html page with script and CSS tags at the top, images in the middle, and script tags at the bottom.

- browser downloads the actual html file

- browser parses the html file starting from the top and going down to the bottom

It does this synchronously. If there is a <script> file on line 8 will it wait for that script to download and run through once before proceeding to line 9.

- as it goes down the html file the DOM is being built at the same time, line by line.

- say that after line 90 there are no more DOM elements. The DOM is then completely loaded and created at this point.

- say that line 90-100 are script tags. Those script tags are then loaded and parsed and run. So if there is any jQuery in those scripts that need to select a DOM element, they can, because the DOM has been 100% loaded. *If* those same script tags had been added at the top, those DOM elements would not have been created at the time the script runs, so things would break.

- I'm confused when rendering happens. Does rendering also happen line by line as the html is parsed, or only after the entire DOM is built?
 

KB

Diamond Member
Nov 8, 1999
5,406
389
126
Each browser may do these order of operations differently. I remember running into an issue with IE 6.0 in which if I had script code at the bottom of the file it would run before the DOM was finished loading and it would error out. I am not sure if it still happens in IE 11.

This is why most people who use jQuery put initialization code in the document ready handler. That way you know the DOM is finished loading.

$( document ).ready( handler ) ;

http://api.jquery.com/ready/
 

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,695
4,658
75
In general: It's complicated, and some of it depends on the browser. Chrome seems to start displaying stuff before it's done parsing the DOM; Firefox seems to wait until the DOM is ready.

See also: http://css-tricks.com/thinking-async/ for information on when scripts are run and when they block other stuff.
 

purbeast0

No Lifer
Sep 13, 2001
53,636
6,513
126
while this may not be related to issues you are having at all, but if you are having issues with timing then you should look into promises. once i learned how promises work it really helped a lot of stuff to happen sequentially but wasn't happening sequentially due to the nature of async web apps.
 

Rakehellion

Lifer
Jan 15, 2013
12,181
35
91
Don't rely on it happening in any order. If necessary, use server-side scripting or AJAX to make sure things happen on time.