There are many elements that are being loaded and applied at many different points throughout the page load process. Many of these tasks occur concurrently with others. The main three client side technologies that are rendered and executed being HTML, CSS and JavaScript. PHP/server-side technologies are all created before page load and then rendered in the same fashion as described below. This post will cover the relation between HTML and JavaScript.

Top to Bottom

Both HTML and JavaScript execute from top to bottom. This is a basic html page with an import of jQuery and just a single <p> tag. So with this top to bottom idea in mind anything the <head> tag loads before the <body> tag.

Proving this with JavaScript

So I can tell you that this loads before that, great! Let’s actually see this at work though!  I will first prove that a script tag at the end of the page is going to modify our paragraph by modifying the text. I will then break it to show that we cannot change it if the script is above the paragraph in the HTML. Here the script tag work at replacing the text as we would expect it to:

JavaScript in the Head Tag

However if we move this JavaScript into the <head> tag, where on often finds JavaScript  and imports of external JavaScript files, our paragraph text is not replaced:

JavaScript Function to Wait for HTML Document

One can still have JavaScript execute in the <head> of the HTML with the widely accepted and used $(document).ready()function.  This uses jQuery to target the document and wait for it to be ready. So the document (the D in DOM stands for document) is ready for JavaScript to target elements because all the HTML has been rendered.

JavaScript Function to Wait for All Window Elements

Another example of the code working from top to bottom may be seen below. Here I have just moved the script tag to before our import of the jQuery library.  So this script will not run because we are using the jQuery $ selector.

JavaScript Function to Wait for HTML Document

One may also need all of the pages elements such as images to be loaded. A reason for this may be to resize something based on the height of sibling elements. So if one needs everything on the page to be loaded instead of the $(document).ready() one can simply wait for the whole window to load with $(window).load(). Example: