Friday, March 31, 2006

Document loading order

The other day I was learning about how a document is loaded by a browser. I use the <script> tag to insert definitions of different variables at different stages of a document(#2). Then I wrote a function showVars() to check the availabilities of those variables (#1). This showVars() is called at different locations (thus different stages during loading steps) of a document(#4). The output will tell us how a document is loaded.

Other than those defined variables, showVars() also checks the availabilities of document.body and a <div> that is placed in the end of the <body> (#3).



The result shows some interesting features:



-- Retrieving a tag from inside <body> section by document.getElementById() works even before the document starts loading (#1);

-- document.body is available for javascript right after the loading enters <body> tag (#2)-- doesn't have to wait until the entire loading process is completed;

-- A javascript variable V defined with a <script> tag that is inserted into <body> section is availabe only to those javascript code AFTER V is defined;

-- A javascript in body.onload (<body onload="??">) is executed after all elements are loaded, so it can access all of the variables defined anywhere in the document (#7).
javascript, dom


Related

Dean Edwards: The window.onload Problem - Solved!
http://dean.edwards.name/weblog/2005/09/busted/
http://dean.edwards.name/weblog/2005/09/busted2/