Saturday, 3 March 2012

Best Practices to Enhance Performance of Website

Performance of a website can be visualized in two ways:

  • Server Performance
  • Perceived Performance
Server Performance is concerned with the number of request a server can handle at a time and time taken to process request

Perceived Performance is concerned with speed of website from visitor(end user) perspective. Even if the server performance is high , site might appear slow to visitor because of poor client side performance and due to this visitor can distract away from your website. 

There are several areas in which performance can be improved. But as front end is most commonly accessible part of website by visitor so client side performance matters a lot. Thus for the user, it is the speed of Web page delivery that indicates the performance level, not how fast the application is executed on the server. In this blog I will throw light on ways to enhance client side performance of website.

Minimize HTTP Requests

Yahoo did experiments on improving performance of website and concluded that popular sites spend 5%-38% time downloading HTML document, remaining 65%-95% time is spend in making HTTP request to get the components(Images, Stylesheets, Scripts, Flash and more...) used in HTML web page. More component used, more will be the HTTP request, But in rich UI web pages, components used are more but you have several ways to minimize HTTP request while also maintaining rich UI design web pages.

Combining Script / Style sheet files into single file :
By combining all scripts file into a single script file, and similarly combining all CSS into a single style sheet you can reduce number of HTTP request.

CSS Sprites: 
You can reduce number of image requests and even over all size of image by combining all images into a single image(sprites) and can use background-image and background-position properties to display the desired image part. Creating sprites is hard, requires arcane knowledge and lots of hit and trial efforts. But no worries there are web services like SpriteMe available which can help you in creating sprites.

Image Map:
Image Maps are used to combine multiple images into a single image. The overall size is about the same, but reducing the number of HTTP requests speeds up the page. Image maps only work if the images are contiguous in the page, such as a navigation bar. Defining the coordinates of image maps can be hard and error prone. So this is rarely used technique.

Use Content Delivery Network

Most of the end user time is spend in loading component of web page like image, script, style sheet, flash etc. So to reduce loading time, it is possible to disperse contents. This can be achieved by CDN. CDN is a group of servers around the world, optimized for fast delivery of static files and positioned to be as close as possible to your site's visitors.

 Advantage of using CDN 
  • CDN servers are faster and closer to your visitors. 
  • They're also usually on another host like cdn.example.com for your site. This means your browser will open 5 requests to example.com and  5 requests to cdn.example.com at the same time. Allowing it to load even more at the same time. 
Some large Internet companies own their own CDN, but it's cost-effective to use a CDN service provider, such as  Akamai Technoligies , Edge Cast, Level 3 etc. For small companies and private web sites, the cost of a CDN service can be prohibitive, but if the target marget is large and global then CDN is necessary to achieve fast response times of website. 

Caching:

Web servers and browsers use a tool called a cache to help pages load more quickly. When browser cache is unable, the first time you load a web page, it is loaded straight from the server, but if later during the same session if you make request for the same page, then it is loaded from browser cache instead of making HTTP request for the same page. This loads the page quickly and reduces strain on server cache can be controlled by the user  at browser level and the Web developer at server level.

Three Ways to control Server Cache

  • Via <meta> tags (<meta http-equiv="Expires"...>)
  • Programmatically by setting HTTP headers (CGI scripts etc.)
  • Through web server configuration files (httpd.conf)
Use HTTP Compression

Time taken to transfer HTTP request and response across depends on network bandwidth and network traffic. End user bandwidth and internet service provide are beyond control for development team. But still this response time can by reduced by compressing HTTP response.

 HTTP/1.1 web clients indicate support for compression with the Accept-Encoding header in the HTTP request.
      Accept-Encoding: gzip, deflate


If the web server sees this header in the request, it may compress the response using one of the methods listed by the client. The web server notifies the web client of this via the Content-Encoding header in the response.


 Content-Encoding: gzip

Gzipping reduces the response size by about 70%. In Apache, the module configuring gzip depends on  version: Apache 1.3 uses mod_gzip while Apache 2.x uses mod_deflate. There are known issues with browsers and proxies that may cause a mismatch in what the browser expects and what it receives with regard to compressed content.  But Apache modules help out by adding appropriate Vary response headers automatically.
Reduce DNS Lookups
The Domain Name System (DNS) maps hostnames to IP addresses. When you type in your domain name into your browser, a DNS resolver contacts the browser to return with the servers IP. Usually the browser takes some time to complete this process.  The browser can't download anything from this hostname until the DNS lookup is completed. Reducing the number of unique hostnames has the potential to reduce the amount of parallel downloading that takes place in the page. Avoiding DNS lookups reduces the response times.
Reduce  redirects
Ways to redirect user to different URL
  • Server ways (301 and 302)
      HTTP/1.1 301 Moved Permanently
      Location: http://example.com/newuri
      Content-Type: text/html
  • Meta refresh tag and Java scipt 
        <meta http-equiv="refresh" content="5; url=http://example.com/">
    
        <script type="text/javascript">
        window.location="http://www.google.com"
        </script>


Redirect is done to connect the old web page to a new URL. But reducing this to a minimum is the best practice to increase the performance of a web page.Redirects slow down the users experience because inserting a redirect between the user and the HTML document delays everything in the page since nothing in the page can be rendered and no components can start being downloaded until the HTML document has arrived.
One of the most wasteful redirects happens frequently and web developers are generally not aware of it. It occurs when a trailing slash (/) is missing from a URL that should otherwise have one. For example, going to http://example.com/documents results in a 301 response containing a redirect to http://example.com/documents/ (notice the added trailing slash). This is fixed in Apache by usingAlias or mod_rewrite, or the DirectorySlash directive if you're using Apache handlers.
Reduce the Number of DOM Elements
Less DOM elements means better page performance. It means better javascript performance, especially in older browsers.
Example: 
Use
<ui id="navigation">
//code goes here
</ui>
Instead of
<div id="navigation">
<ui>
//code goes here
</ui>
</div>
Use additional element only when required
Place Style sheet in Header
Style sheets to the document HEAD makes pages appear to be loading faster  because putting stylesheets in the HEAD allows the page to render progressively. This is especially important for pages with a lot of content and for users on slower Internet connections. The HTML specification clearly states that style sheets are to be included in the HEAD of the page, A, [LINK] may only appear in the HEAD section of a document.

Place Scripts at the Bottom

Scripts causes progressive rendering to stop for all content below the script until it is fully loaded. Moreover, while downloading a script, browser does not start any other component downloads, even on different hostnames. 
In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. 
Alternative solution is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering.  If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.

Avoid CSS Expressions:

CSS Expression have become deprecated since IE8
Example of CSS Expression 
 The background color could be set to alternate every hour in below CSS expression
 background-color: expression( (new Date()).getHours()%2 ? "#B8D4FF":"#F08A00" );


In above example , the expression method accepts JavaScript expression. CSS property is set to the result of evaluating the JavaScript expression. The expression method is ignored by other browsers, so it is useful for setting properties in Internet Explorer needed to create a consistent experience across browsers.
One way to reduce the number of times your CSS expression is evaluated is to use one-time expressions, where the first time the expression is evaluated it sets the style property to an explicit value, which replaces the CSS expression. If the style property must be set dynamically throughout the life of the page, using event handlers instead of CSS expressions is an alternative approach. If you must use CSS expressions, remember that they may be evaluated thousands of times and could affect the performance of your page.
Simplify tables and avoid nested tables
If more tables /layout are nested,longer it will take for the Web browser to render the Web page.
Minify Javascipt and CSS
Minification is the practice of removing unnecessary characters from code to reduce its size, thus improving load times. When JS/CSS code is minified all comments are usually removed, as well as unneeded "white space" characters like space, new line, and tab. Various online tools are available to minify js ans css files.
Optimize Images
Optimizing images reduces the size of image without doing any harm to image quality. Optimized image takes less time to load on a web page. Various online tools are available to optimize images. One of them mostly used is Yahoo Smush.it


Make Ajax Cacheable

No comments:

Post a Comment