- 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 3: Keep CSS and JavaScript out of your markup
One corollary to “use Web standards” (step 1) is “ensure separation of presentation and behavior from content” – one of the fringe benefits of doing so, as you’ve probably guessed, is improving page load and rendering times.
If visitors to your site engage in multiple page views and return to your site frequently (and you hope they do!), you can optimize those repeat visits by moving all inline CSS to an external style sheet and all inline JavaScript blocks to an external file. Not only does this shrink the size of your HTML file and facilitate sharing that code across multiple pages, but it means creating assets which are cacheable by the browser.
Just in case the browser cache is a nebulous thing that you’ve never quite understood, let me give a vastly simplified explanation. When a user enters a URL, the browser connects to a server and obtains some HTML. The browser parses the markup to identify external objects which need to be retrieved. The browser first checks the local cache to determine if any of those files have already been downloaded; if not, it proceeds to download those external objects. All of those objects will live in the browser cache for a period of time – exactly how long is determined by settings on the server as well as the user’s browser preferences.
Let’s assume the cache lives at least as long as the browser is open. In this scenario, when the user navigates from one page to another, provided the same CSS and JavaScript files are called, the browser will use what’s already in the cache, rather than download new copies of the files. If the files live in the cache for a longer period of time – say, 30 days – then the browser will continue to use the cached files. If your CSS and JavaScript files are large, this can save the browser from downloading the same data over and over!