Execution order
When does the script get executed?
It’s important to understand that JavaScript code will be run at different times during the page’s loading process, or even after. You can place code in a number of areas of a page: within the HEAD tag, the BODY tag or explicitly in elements within the BODY.
Consider the following markup:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Hello there</title> <script> // you can put your script here in the HEAD </script> </head> <body> <script> // you can put your script here in the BODY </script> <p>Or you can put it in an element like this <a href="http://www.buyco.ca" onclick="javascript:void(0);">link</a></p> </body> </html>
Order of script execution
- <HEAD> tag
- <BODY> tag
- on DOM load
- on PAGE load
This is most simply the order of script execution on your page. Before we get too deep into the mechanics of event handling, I will explain in the simplest terms what DOM load and PAGE load is. They are not specific areas where you can drop your code, rather they are points in time during the process of a browser loading the page and it’s contents. You can write scripts in the HEAD and BODY which tells your browser to execute scripts at those two points in time.
The moment at which the document is loaded and ready, but before any external references are even downloaded yet, is DOM load. By external references, I am talking about images, referenced style sheets, etc. After the document is ready, your browser starts to download those external resources (images, stylesheets, etc). When those resources are completely downloaded and displayed, this is the point in time when the PAGE is loaded.