- Step 1: Use Web standards
- Step 2: Validate your HTML and CSS
- Step 3: Keep CSS and JavaScript out of your markup
- Step 4: Load CSS in the HEAD, JavaScript in the BODY
- Step 5: Reduce requests for external objects
- Want to learn more?
Step 4: Load CSS in the HEAD, JavaScript in the BODY
While style sheets must appear in the HEAD of your pages, remember that JavaScript can be loaded in either the HEAD or the BODY – and the longer it can wait, the faster your page will render.
If you want your HTML to validate, you must locate all CSS in the document HEAD – but if you want a fast-loading page, loading all CSS in the HEAD is a necessity. Browsers wait until all external CSS is loaded before starting the page rendering process – and any CSS found in the markup can cause portions of the page to be redrawn, showing the user a page which shifts as it renders. So, put all of your CSS in the HEAD – I like to insert a LINK tag just after the TITLE – to help the browser load and render CSS quickly.
JavaScript, on the other hand, should be loaded as late as possible – ideally just before the closing BODY tag in order to optimize page rendering. Why there instead of in the HEAD or elsewhere in the BODY? Because you don’t want the browser to block the loading of external CSS, images, and other assets while it’s downloading JavaScript.
If you’re scratching your head, wondering what I mean by blocking, then let me explain. Browsers, by default, try to help you with optimizing page load times by downloading multiple external assets simultaneously. If you have a very simple Web page with no CSS or JavaScript and just two images in the BODY, the browser will request both images from the server simultaneously. However, if you add an external JavaScript file call to the HEAD of your simple page, those two images won’t be requested from the server until the JavaScript file has been downloaded.
Why does the browser do this? Think about a page that calls multiple scripts and what would happen if the browser didn’t wait for one script to download before downloading another. If the JavaScript files were of different sizes and were interspersed in the markup, they might be downloaded and executed out of order. If a script were to conditionally call additional scripts or require variables to be set by another script, then a wrong result or an error might be generated.
If you write your JavaScript to be applied as a “progressive enhancement” (the second corollary of step 1, “use Web standards”) then relocating the call to the end of the markup shouldn’t be any problem. If you haven’t yet practiced this technique, now would be a great time to try it!