Curated by: Luigi Canali De Rossi

Monday, January 18, 2010

How To Make Your Website Faster - Part 2: How To Optimize Your Website Code For Speed

Knowing how to make your website faster will soon become a core requirement for any serious web publisher. As a matter of fact, as I have mentioned in Part 1 of this guide, Google will soon start using the speed response of your web site together with the other factors that determine your ranking in the Google SERPS. Are you prepared?

Photo credit: norebbo

In Part 1 of this guide you have already found useful tools and tutorials to speed up your website, while in this second part you will have the opportunity to learn in-depth, from MasterNewMedia very own technical director, Drazen Dobrovodski, what should be another crucial element of your speed-up strategy: how to optimize your website code.

This guide can be read and understood by non-technical people, and it is in fact devoted to those who need to decide and coordinate such web site performance optimization tasks as well as to those who will actually perform them.

At the same time, while you don't need to be a programmer to understand most of what is written in this guide, it does help if you are a competent technical person or if you have someone who can assist you in implementing some of these speed optimization techniques.

In this section of the guide, you will find a detailed manual on how to optimize your web site code in order to make your web site significantly faster than it is now.

You can in fact test and measure your page load speed against the one of your most relevant competitors, while making sure that you are at least as fast as them, if not faster.

Here the key points covered:

  • When to use static vs. dynamic pages,
  • How to manage external requests efficiently,
  • How to take advantage of your CSS,
  • Which elements to prioritize in your website code,
  • How to put your website code on a diet.


How To Optimize Your Website Code For Speed

by Drazen Dobrovodski

1. Avoid Dynamic Page Creation


If you are creating your static HTML pages by yourself you can skip this step. However, this would probably only be the case with people who are making a few hobby pages or a small company site that is more of a "business card on the web" then anything else.

Any website with more ambition is usually coming from some publishing platform like Movable Type, WordPress, or a content management system like Drupal.

Most of these will generate dynamic content by default. This means that for every visitor to any of the pages a CGI or PHP script is running a database query to get the template (looks) of the page, then the page content (text and images) and then combines them to serve all this to the visitor.

It doesn't take a rocket scientist to figure out that if you get 1000 visitors, this means at the very least 2000 database queries and a lot of processing time to "dress" your page text into the template. All that on top of the 1000 HTTP requests that server will have to handle.

Using static HTML pages is much faster and much easier on the server so you should do it as much as you can.

This is such a big point that all major publishing platforms and content management systems that I can think of have the ability to pre-cache the pages. By that, visitors can get ready-made static pages instead of waiting for the database reads and scripts to form the same pages for each visitor.

To use static HTML pages:

  • In Movable Type: In your publishing settings choose the option to build all templates statically.
  • In WordPress: You will need a WP-Cache or WP Super Cache plugins.
  • In Drupal: Plugins Boost and Advanced Cache will do this for you.


2. Use As Few Includes and HTTP Requests As Possible


Almost all pages and templates today use images, JavaScripts, Flash and includes. For each one of those, the web server has to establish a connection, check file permissions, send headers, etc... Each one of these increases the loading time. Then again - all those things are there for a reason. They are needed.

So how do you preserve your images, JavaScript and includes while still keeping the number of elements down? You group as much of them as possible into one file.

2.1 Grouping Images Into One File Using CSS Sprite

CSS allows you to merge several images into same image file and then position that same file differently so that only one section of your liking gets displayed in any given place in the page.

This is your image:

This is your image with sizes in pixels.

Now your first DIV layer for the "SuperGreatLogo" would then be 194px wide, 33px high and would start at top left of the image (zero offset from top, zero offset from left).

#supergreatlogo {
background: url( no-repeat 0px 0px;

In HTML you display it with a simple line:

<div id="supergreatlogo"></div>

And this is how it looks:

Your "Menu Item" as we can see is 43px high and 194px wide. It starts at zero left offset and 33px top offset. So the CSS for our "Menu item" would look like this:

#ourmenuitem {
background: url( no-repeat 0px -33px;

In HTML you display it with a simple line:

<div id="ourmenuitem"></div>

And this is how it looks:

"Icon1" part of the image is 36px high and 89px wide. It starts at zero left offset and 76px top offset. So the CSS for it is:

#ourIcon1 {
background: url( no-repeat 0px -76px;

In HTML you display it with a simple line:

<div id="ourIcon1"></div>

And this is how it looks:

Finally, "Icon2" is 36px high and 105px wide. It starts at 89px left offset and 76px top offset. So the CSS for it is:

#ourIcon2 {
background: url( no-repeat -89px -76px;

In HTML you display it with a simple line:

<div id="ourIcon2"></div>

And this is how it looks:

Using CSS sprites you can merge all your website interface images into one, thus drastically reducing the number of the HTTP requests. Depending on the complexity of your site interface this can be a major speed-up factor.


2.2. Grouping JavaScript and PHP / ASP / JSP Includes

If you already coded something in JavaScript, PHP or any other language, then you know that it isn't much of a problem to merge the code. The problem starts if that script has to display something in an exact place on the page.

How can you merge JavaScripts if one writes out something in the header, the second one something in the side column and the third one something in the footer?

The answer is: using JavaScript innerHTML property. It allows you to change - well - the inner HTML of any element you specify.

Have a look at this example layout:

var myTopText="Text for the header";
var mySideText="Text for the side div";
var mySideText="Text for the footer";


Using this method, you can merge several JavaScripts, or server-side (like PHP) includes and still direct their outputs anywhere you want them in the page.


2.3 Use Relative Paths Instead of Absolute Paths

Instead of calling your images using:

img src=""

use a relative path to the file on the web server like this:

img src="../images/extra-pretty-images/image.jpg"

Obviously this code changes depending on the position of your HTML files, but once you substitute all absolute image paths with relative paths, your server will no longer have to re-establish a connection for each image in the page.


3. Take Advantage of Gzip Components


All recent versions of web browsers have the ability to accept Gzipped content (and it goes back as far as IE4 and Netscape / Mozilla 6 and 7 versions). This means that you can compress all of your CSS and JavaScripts with Gzip and web browsers will still display them normally.

The page you are reading uses Gzip for CSS and several JavaScripts. Images like JPEG are already compressed so you will leave them as they are, but if you pre-compress your CSS and JavaScript you can significantly reduce the size of the files being transferred. This both speeds up the page loading and also reduces your bandwidth.

Let's explain it on a CSS file.

First you Gzip your file and upload it to a server. Now you change the CSS call in your pages to reflect the new GZ extension. For example:

<link rel="Stylesheet" target="_blank" href="" type="text/css" media="screen" />

Now in your /css folder make a .htaccess file with following code:

AddEncoding x-gzip gz
AddType 'text/css; charset=UTF-8' .gz

The first line declares that files with extension "gz" are in "x-gzip" encoding . The second says that they are to be sent out with "text/css" header so that browser knows how to use them.

To do this for JavaScripts, make a separate folder (for example /js) and add the same .htaccess lines only using "text/javascript" instead of "text/css".


4. Reduce The Number of DNS Lookups


In section 2.3 I already discussed replacing absolute paths with relative paths. However, if your images (or other components) are on a separate web server, then using a code like this:

img src=""

forces the user's browser to perform a DNS lookup.

You see the real address of your website is not "" (or whatever it is). Its real address is an IP number. The IP address consists of four numbers, each 1-3 digits in length divided by dots. For example: IP is Yahoo!, is MasterNewMedia and so on.

Every time you use an address like "" in your page code, the web browser first has to perform a DNS (Domain Name Service ) lookup to see which IP is associated with the domain Name "". Needless to say, this takes (wastes) time.

To avoid this (and the content is on a separate server and thus you can't use relative path), use the IP address instead of domain name like "".


5. Use Caching As Much As You Can


Some tutorials put a lot of emphasis to everything cache related such as expiration headers. The value of this depends on the kind of traffic your site gets.

You have to know your site. It is not rare for websites to have 80% first-time visitors who just arrive through some search engine(s).

  • If your audience is primarily such one-time visitors, then caching files will not bring you much speed increase.
  • If your audience is predominantly in repeat visitors, then caching is a major factor.

5.1 Put JavaScript and CSS Into External Files

Browser will cache CSS and JavaScript and re-use them when visitor goes to other pages. This way you don't have to load the same CSS and JavaScript code in every page.


5.2 Add an "Expires" Header With The Date In Distant Future

You can do it for any given file type in .htaccess like this:

<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Expires "Thu, 15 Apr 2020 20:00:00 GMT"

The above example is for images and Flash files, but you can do it for CSS and Javascript files as well.


5.3 Configure Etags

Etags are sent in HTTP headers for each file. Then the web browser can compare the Etag of the files it has cached with the file on the web server and then if the Etags match, the web browser uses the cached file instead of downloading it again.

Etags allow you to be flexible with the cache. If you don't need that flexibility (for example for images in your pages, css etc), you can just turn Etags off and the web browser will be using other methods to decide whether or not to use the cached copy. So if you already added the above lines from point 5.2 to your .htaccess, then you can just use this line:

FileETag none


6. Save Web Browser's Time On CSS and JavaScript


6.1 Avoid CSS Expressions

CSS Expressions are a feature in IE that is not supported by other browsers. It allows you to place non-fixed values in the CSS. For example:

width:expression(document.body.clientWidth > 1024? "1024px": "auto" );

It takes time for web browsers to interpret this and only IE supports it, so just avoid it.


6.2 Reduce The Number of DOM Elements

Every DIV layer, every link or form of every page, all those (and more) are DOM (Document Object Model) elements.

If you keep the number of DOM elements down, the browser will spend less time matching them with the CSS and construction the page.


6.3 Put CSS At The Top, JavaScript At The Bottom

If you load the CSS at the top of the page (ideally in the <head> section) then as the page loads, the web browser will be able to format it correctly.

Otherwise the web browser it will have to go through the page code until it "arrives" to the CSS and and then go back to format the page sections loaded before CSS. Obviously this is not an efficient way to go. Just to make things clear - wherever you put the CSS, the amount of data traveling between the server and the visitor will still be the same. However, all the page content that gets loaded before the CSS will show up unformatted. Then, when the browser finally reads the CSS, it will go back and start formatting that content. This looks like chunks of text being moved around and dressed into different fonts and colors, and visitor perceives this as page loading time.

JavaScript will block parallel downloads. This means that your web browser must wait until the script is loaded and executed before it proceeds with loading anything that is after that JavaScript code (images, Flash, even CSS if you placed it below JavaScript).

JavaScript also depends a lot on page elements. If you refer to section 2.2, you see one example of that. If you load the given JavaScript on the top of the page you will get an error. JavaScript got loaded before the element IDs were established and thus it can't find what ID you are referring to.

All things considered, it is best to keep JavaScripts at the bottom of the page code.


6.4 Minimize The Number of Lines Used In JavaScript and CSS

In any normal circumstance this item is not a major factor, but it deserves its place in the list.

All comments, newlines, double spacing, etc. simply increase the file size of your CSS and JavaScript. If you have a lot of them, it can add up.

You can do it yourself or you can download YUI Compressor to minify CSS and JavaScript for you.


7. Keep Your Cookies Small


If you use cookies, try to keep them as small as possible. Cookies get loaded with the headers before the content so if they are small this gives the user a faster page load.


8. Avoid Redirects


Redirects are used to (surprise, surprise) automatically redirect users from one URL to another. This can be done because an old URL is no longer used, because you are sending the user to a login area, etc.

Redirects are not something that every website uses (hence a place #7 on the list). Some web sites do use them but are not in a position to influence / remove them.

For example, if you use the WordPress publishing platform then you don't get a choice. WordPress will add a redirection into your .htaccess file and if you remove it, the web site is defunct.

Still, you should keep in mind to use redirects sparingly because they add time to the page load.


9. Use a Content Delivery Network


This is only for big players.

We already mentioned in Part 1 that the speed of content delivery depends on the proximity of the audience to the server.

When you have an international web site you can place your content (or at least static components of it) on several servers on several geographic locations, thus making it closer and faster to a greater number of people to load your web pages. Again, this is only something useful for big web sites.



Speeding up your web site depends on a number of factors. Over here I touched only the general ones that most users will be able to use.

To get suggestions more targeted toward your specific website you can download Google Page Speed or Yahoo! Yslow.

Yslow will even give you a grade for the items that add or diminish your web site's speed. Realistically, if you test Yahoo's Yslow by pointing it to some of the Yahoo's pages like this one: then you realize that this page gets a mere C. The point is: don't take this "grade" too seriously.

Some of the suggested tips and steps are only feasible for bigger web sites (content delivery network being an obvious example).

Also keep in mind that adding any third party content such as widgets, ads or buttons means that your number of DOM elements goes up and same goes for number of HTTP requests, DNS lookups, uncompressed components, cookies etc. The more of those you use the more your site speed depends on the components out of your control.

Each web site is different and for each web site there is some realistic point up to which the optimization is feasible or meaningful.

Lastly, just as a side note, I am keeping an eye on the SPDY protocol. Google is pushing for it so this could become a major issue soon.

Right now all Internet addresses start with "http://" because all web pages use HyperText Transfer Protocol (HTTP). HTTP was created back in time when Internet was accessed with 9600 KB (and slower) modems and web pages were just academic text with maybe an image chart or two.

This new world of Flash, CSS, image rollovers and all the bells and whistles of today are simply not what HTTP was made for.

SPDY should bring the transfer protocols up to speed with 21st century content, but most, if not all of the speed-up suggestions listed here, will still help you to shave off those few extra seconds from your page load time.

End of Part 2 -- Part 1 here

Originally written by Drazen Dobrovodski for MasterNewMedia, and first published on January 18th, 2010 as "How To Make Your Website Faster - Part 2: How To Optimize Your Website Code For Speed".

Photo credits:
Avoid Dynamic Page Creation -norebbo
Use As Few Includes and HTTP Requests As Possible - John Takai
Take Advantage of Gzip Components - Kirsty Pargeter
Reduce The Number of DNS Lookups - pixbox
Use Caching As Much As You Can - Stepan Popov
Save Browser's Time On CSS and JavaScript - mipan
Keep Your Cookies Small - superdumb
Avoid Redirects - hypermania
Use a Content Delivery Network - adistock

Drazen Dobrovodski -
Readers' Comments    
blog comments powered by Disqus
posted by Daniele Bazzano on Monday, January 18 2010, updated on Saturday, June 25 2011

Search this site for more with 








    Curated by

    New media explorer
    Communication designer


    POP Newsletter

    Robin Good's Newsletter for Professional Online Publishers  



    Real Time Web Analytics