When a user types a URL into the browser or clicks on a link, the browser makes a request to the server hosting the website. The server then sends back the necessary files, including HTML, CSS, JavaScript, and media files, for the browser to display the webpage.
The rendering process generally involves the following steps:
- Parsing HTML: The browser starts by parsing the HTML document to construct the Document Object Model (DOM) tree. The DOM represents the structure of the page.
- Fetching Resources: While parsing, the browser also identifies external resources like CSS, images, and JavaScript files. It then fetches these resources from the server or local cache.
- Building the CSSOM: Parallel to constructing the DOM, the browser also constructs the CSS Object Model (CSSOM) tree by parsing all the fetched CSS. The CSSOM represents the visual layout of the page.
- Executing JavaScript: JavaScript is either executed as it’s encountered in the HTML or deferred until the DOM and CSSOM are built, depending on how it’s implemented.
- Rendering: After the DOM and CSSOM trees are constructed, the browser combines them into a render tree, which contains only the objects that will be visible on the page. This render tree is then used to layout and paint the actual visual elements on the screen.
- Reflow and Repaint: If there are dynamic elements or interactions on the page (like hover effects), the browser may need to re-calculate the layout (reflow) or redraw parts of the screen (repaint).
Understanding these steps helps you recognize the areas you can target for optimization. For example, minimizing HTTP requests and optimizing images primarily affect the “Fetching Resources” stage, while leveraging browser caching can reduce the workload during the “Rendering” phase.
In the chapters that follow, we will discuss various techniques to optimize these stages and enhance your website’s loading speed.