Sunday 6 July 2014

How to minimize http requests

When it comes to website performance, number of requests made by your website to the server plays important role in total page download time. Since every request made includes round trip to server ( request and response ), it adds extra download time i.e total time spent during the trip. Also there are some limitations in the browser that how many parallel requests can be made to single domain. In a nutshell too many requests may decrease your website performance. Now we are going to look how can we minimize or reduce the number of HTTP requests.

Combining CSS and JS files to single file

Having lots of separate CSS and JS ( javascript ) files increases the number of requests made to the server. Suppose you have included 5 different CSS files in your head section and 5 different javascript files in your page. Then total number of request made for these files only will be the sum of number of CSS files and number of JS files. ( i.e 10 ). Your page will make 10 request to server to download necessary files. If you take average round trip for single file as 100 milliseconds, then for 10 request it will take 1 second to download all the 10 files. So by combining them in 1 corresponding file will reduce the number of request to 2, thus reducing download time to 200 milliseconds.

Minimizing HTTP request by Image sprites

One of the major cause that increases the number of HTTP request is separate images files. If your page uses to many <img> tags then for each image, browser sends a separate request to server for that image file unless files are same. To overcome this you can add all your images to a single image called image sprites ( A collection of images put into single image ). Now with the help of CSS, we can show just the part of the image that we need. To show only the part of image we use background-position property for the element. With this property we can specify which portion of the image sprite should be visible from the top left corner of the element.

Ex: Below image sprite contains two images ( Left navigation and right navigation ). We know the dimension of each of these images i.e ( 40 X 40 here). Now we add css to two html element of same size ( 40 X 40 ) to display left and right navigation from the image sprite ( imageSprite.png ).





Now we will take two div's which will be showing these two images.

<div class="left"></div>
<div class="right"></div>

CSS

div {width:40px;height:40px;}
div.left{background:url('yourdomain.com/arrows.png') no-repeat; background-position:0px 0px;}
div.right{
   background:url('yourdomain.com/arrows.png/arrows.png') no-repeat;background-position:-60px 0px;
}

See the demo

No comments:

Post a Comment