Click here to Skip to main content
Click here to Skip to main content

Speed Up Your Website - By Example

, 26 May 2008
Rate this:
Please Sign up or sign in to vote.
Learn how to optimize web page for better user experience
  • Download Examples AllInOne.zip - 37Kb - AllInOne.zip includes (cut-n-paste ready): Optimized HTML Web Templates, CSS Rollover, CSS Sprites examples etc.

Introduction

"We live only to discover beauty, all else is a form of waiting. Khalil Gibran", if you agree with this saying, then you are well aware of what it mean to minimize wait for your web audiences.
Building an HTML page, adding images, CSS and JS has become piece of cake over last few years, but delivering these rich-contents with a Performance to client browser is still a daunting task. This narrow down check list will help you to review your web site to minimize download time.

Note: This article describes only Front-End engineering issues, No Programming/CGI scripting/Data Structure/Database/Multimedia optimization techniques are discussed in this article.

Background

Last year while working on WNetwork.com and Treehousetv.com, I decided to write down experiences I had in my last few years in web development as well as learning from many sources and trying to make a habit of applying them. I have compiled these notes with a hope that every reader will get at least one or two ideas from them.

Laying the Groundwork

In first section we will see Where time is spend, then in second section we would see Why and How that time can be minimized, and then in third section we would summarize some concepts and list tools.
  • SECTION A: Behind the Scene
  • SECTION B: Optimize the Load Time
  • SECTION C: Tools

SECTION A: Behind the Scene

This section describes about what happens in between, when user types WWW address and see complete web page before his/her eyes. This would give us an idea about Where time is spend and how to minimize it.

Click so see larger image.
Please note: Above figure may seem complex but DNS look up normally takes less than a second, approx.: 100ms to 900ms. The detail is given to show a complete process.

Click so see larger image.

Click so see larger image.

Click so see larger image.

Click so see larger image.

Click so see larger image.

Now let's get to the point:

SECTION B: Optimize the Load Time

Following guidelines are based on the collection of common knowledge and experience, and application may vary from situation to situation. I would suggest to Log current web site loading statistics and analyze with results after applying any guideline.

1. Reduce number of HTTP requests

  • Why?
    • Making a connection with the Web Server is a time and network resource consuming process (which involves software/hardware handshaking, data packet(s) transfer, data packet loss, resend, verification process and closing connection etc), and one of major time spend areas.
    • Web Client (Browser) sends separate request for each resource after/during loading a main resource (e.g.: index.htm and then global.css, spring.css, logo.jpg, menu1.jpg, menu2.jpg, menu3.jpg, 1x1.gif, corner1.gif, common.js, validation.js etc...)
    • Technically, after/during loading main page (index.htm), Browser extracts {URL}s from all src={URL}, HEAD-LINK's href={URL} and CSS's url({URL}) tags and then sends separate request for each resource.
    • Generally, Browser downloads only 2 to 4 resources in parallel per host. (depending on HTTP version and Browser. Firefox seems better than IE.)
    • Conclusion: The fewer requests/connections Browser have, faster response will be.
  • How?
    1. Minimize the number of files (CSS, JS, IMAGES etc).
    2. Combine files: (wherever possible)
      • All CSS files into one file.
      • All JavaScript files into single file.
      • Even image files into one file wherever possible: Use background-image and background-position to display required "window" of image. (See example CSS-Sprites.html in AllInOne.zip)
    3. Use Browser Cache:
      • On first visit, Browser have to download all resources, but on Second visit, why should not Browser get resources from Cache (previously loaded and saved resource - estimate is 50% to 60% of user Browsers are set to Cache). So optimize your pages to use Browser's Cache where ever possible.
      • Use of "Expires" header with future dates would save time on next visit. Browser would use cached version of object as long as it is not expired or deleted.
        For HTML pages:
        <html>
          <head>
            <title>Cache - Example</title>
            <meta http-equiv="Expires" content="Sat, 16 Jul 2016 18:45:00 GMT">
            .....
          </head>
        
          <body>
          .......
          </body>
        </html>
        <html>
        
        
        For Images/CSS/JavaScripts, configure Web Server as follow:
        • IIS: In IIS, right click on Folder Or File > Properties > HTTP Headers > click on Enable Content Expiration > Expire on {set future date} > click Apply. See example below for folder images:
        • Apache: use mod_cache, mode_file_cache modules to configure caching.
      • Do not Cache Dynamic HTML page, see example below:
        <html>
          <head>
            <title>No Cache - Example</title>
            <meta http-equiv="CACHE-CONTROL" content="NO-CACHE">
            .....
          </head>
        
          <body>
          .......
          </body>
        </html>
        
        
      • Catch/Challenge:
        • What if some objects (JavaScript etc) are changed later?. Then try using file names like "JsFunc_5.2.3.js" for new versions (or reconfigure ETags).
        • Another thought: Don't cache HTML and cache every thing else. [you can simply rename object names (modify Urls) in HTML to force Browser to load newer version next time].

2. Proficient <HTML>

  • Why?
    • Generally, HTML takes only 20% of time while others (Scripts, CSS, Images) takes 80% of download time, which means we need to reduce size of HTML as well as "help" Browser to render it as quickly possible.
    • HTML is a master wrapper of all of objects and styles, and is essential for Browser to understand, unwrap and render it correctly. Because of poorly implemented X/HTML/CSS Standards and Browser wars, Browsers are build with two modes: Standard (Fast mode, Browser trusts HTML page developer), Quirk mode (Browser have to validate HTML/CSS, find and "forgive errors").
  • How?
    1. Minimize Download Time:
      • Can page be reduced in size? User may like to spend 2 seconds for each of 5 pages instead of 10 sec for one page (i.e.: Split page into smaller pages and create links to other pages). On the other hand, user may like to read all at once, so better way could be middle of these two.
      • Eliminate unnecessary whitespace, unwanted/unoptimized tags and comments. Practically, spaces might by necessary for human readability and maintenance, then use some tools to remove unnecessary spaces just before moving files to production.
    2. Faster Rendering:
      • Very often simple designs are the best. Google's home page is 6 KB and have very simple HTML, this will help Browser to parse and render fast.
      • Standard vs. Quirk mode, So let build a trust (that we are professional and follow standards) with the Browser to use optimized HTML parsing. To switch Browser to Standard mode use:
        <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
             "http://www.w3.org/TR/html4/strict.dtd">
        
        <html>
          <head>
            <title>DTD - Example</title>
            .....
          </head>
        
          <body>
          .......
          </body>
        </html>
        
        
      • Move inline scripts and CSS to external file (Reduce the number of inline scripts i.e.: document.write();)
        • Follow this guideline: Browser get confused between rendering content, applying CSS and as well as running Script to alter layout, in this case Browser have to redraw/or halt content rendering. So using external files is better way.
        • Break this guideline: External files mean extra HTTP request and slow downloading. Small Inline scripts and CSS may be good for HOME page for faster downloading and fewer HTTP requests.
      • Chunk your content
        • Replace table based layout with div blocks or break tables into smaller tables. Browser could not render an element until its closing tag is not received. i.e. any object in big outer <table> could not be rendered until its </table> is not received.
        • Write HTML in chunks, use more <div>s and less <table>s.
        • See examples Template1.html..to..Template5.html in AllInOne.zip.

3. Proficient <IMG>

  • Why?
    • Images are one of the big Time and Bandwidth consuming objects to download. Time saved in this regard will improve performance dramatically.
  • How?
    1. Minimize the use of images.
    2. Use CSS rollovers instead of Images in links. (See example RollOvers.html in AllInOne.zip)
    3. Always specify WIDTH and HEIGHT parameters for all IMG. Even for smallest ones.
    4. Carefully choose number of colors and then image format:
      GIF: works best for solid colors and sharp-edged transitions from one color to other, Maximum colors: 256.
      JPEG: works best for continuous gradations of many colors or grey tones.

      When to use GIF examples below:
      GIF JPEG
      Quality: 10%
      JPEG
      Quality: 60%
      JPEG
      Quality: 100%

      Bytes: 156

      Bytes: 379

      Bytes: 433

      Bytes: 434

      Colors: 2
      Bytes: 318


      Bytes: 927


      Bytes: 1,994


      Bytes: 4,037

      Colors: 17
      Bytes: 713


      Bytes: 987


      Bytes: 2,159


      Bytes: 4,928

      Colors: 3+1 (transparent)
      Bytes: 379



      Bytes: 1,249



      Bytes: 2,823



      Bytes: 6,651


      When to use JPEG examples below:
      GIF JPEG
      Quality: 10%
      JPEG
      Quality: 60%
      JPEG
      Quality: 100%

      Colors: 256
      Bytes: 8,693

      [x]
      Bytes: 4,370

      Colors: 256
      Bytes: 6,952


      Bytes: 863


      Bytes: 1,962

      [x]
      Bytes: 5,604
      Please note: Different programs create different image sizes, I used Photoshop CS2, W100xH100 at 72dpi.
    5. Avoid ANIMATED gifs and FLASH (because of long loading time and creates distractions.)
    6. Use background colors, fills and images (with repetition) instead of big images.
    7. Never keep identical images in more than one folder on server. (To avoid two HTTP requests and not getting benefit of first Cached image.)
    8. Load large images in layers/Progressive. Its tricky, try if works, may take longer but user may feel better.
    9. Prefer individual image size less than 10KB, but don't split bigger image into small ones to reduce file size, use CSS sprites or image maps instead. (See example CSS-Sprites.html in AllInOne.zip)

4. Proficient <TABLE>

  • Avoid using one big Outer table, instead use separate tables for header, content1, content2, content3....., footer etc. (See Not-An-Example in Table-vs-Div(1-Okay).html and Table-vs-Div(2-Better).html in AllInOne.zip)
  • Use <div>s instead of <table>s, develop page in chunks (tables or div) instead of big outer table. (See example in Table-vs-Div(3-Even Better).html in AllInOne.zip)
  • Design using nested tables instead of using cell merges and splits. Use separate table wherever possible.
  • Always give the width for each of cells in a table. Make sure that the total of cells in a row adds up to the table width. Use CSS table-layout:fixed (See example Table-ColGroup-2.html in AllInOne.zip) or use COLGROUP tags (See example Table-ColGroup-1.html in AllInOne.zip).
  • When using Width or Height less than 10px, then use 1x1.gif transparent image. (Netscape don't like measurement in percentage.)

5. Order of components in the page

  • CSS:
    • Place CSS on top of page inside HEAD, It helps Browser to know in the start about HOW to style and display content before having all content.
  • JavaScipt:
    • TOP of page (avoid): Only if JavaScript is required for page's initial display then keep it in the HEAD to be downloaded first, otherwise keep DHTML Script at the end of page.
    • BOTTOM of page (ideal): Place JavaScript at the bottom of page as much possible, because Browser may block rendering (or rerender) during downloading in hope of document.write() to induce HTML. Otherwise try to use DEFER attribute:
      <html>
        <head>
          <title>CSS and JS defer - Example</title>
      
          .....
          <link rel="stylesheet" type="text/css" 
               href="rich-layout.css" media="screen">
          <link rel="stylesheet" type="text/css" 
               href="simple-layout.css" media="print">
          <script type="text/vbscript" src="fval1.0.2.js" defer></script>
        </head>
        <body>
      
        .......
        </body>
      </html>
      
      
  • Make CSS and JS external files.
    • Follow this guideline: External files would help Browser to cache for next use and is good for multiple visits.
    • Break this guideline: To avoid extra HTTP request and faster response, inline may be good for home page. (This depend on your website's Page View per session - Google has 1 pv for home page.)
  • Download few basic page layout templates. (See examples Template1.html .. to .. Template5.html in AllInOne.zip)

6. Reduce Request & Response Sizes

  • Why?
    • Generally, 80% to 90% time is spend in downloading HTML and other objects while 10% to 20% in rendering them, so minimizing the download time (by reducing content size) is key to get better performance. One of well supported method is to compress text-based files as gzip.
    • Most Browsers are capable of sending Accept-Encoding:gzip,deflate as part of their request, and in response, server can send Content-Encoding:gzip with compressed data.
    • HTTP compression tends to be more efficient on one large request than several small requests.
  • How?
    1. Compress text-based files, e.g.: HTML, JAVASCRIPT, CSS file(s). Compression can reduce size up to 70%.
      IIS: In IIS Manager, double-click the local computer, right-click the Web Sites folder > Properties > Service > HTTP compression section:

      Please note: You may also need to configure Web Service Extension and Metabase. (You can configure for certain text-based (*.htm, *.css, *.js etc) files.)
      Apache: use mod_gzip, mod_deflate modules to configure compression.
    2. Minification: Remove space, newline, tab, comments; shorter strings, variables and literals; remove duplicate script and use CSS inheritance as much possible.
    3. Reduce Overhead:
      COOKIE: every request have Cookie attached to it forth and back.
      • Size: better if less than 100 bytes, ok if less than 500 bytes.
      • Carefully select domain level, i.e.: .mydomain.com OR finance.mydomain.com
      • Carefully select expiry date. Remove when it is not needed.

7. Reduce Domain Lookups

  • Reduce Domain lookups: Generally, 2 is better than one (To get advantage of Browser's parallel downloading capability) and 4 is worse than 2.
  • Using Browser's Cache will also reduce Domain Lookups.

8. Content Delivery Network: (for specific region)

  • Simply, key is to be as close as possible to the source of request. i.e.: Keeping Web Server(s) close to Client's Browser.
  • Server with fewest network hops is best or Server giving faster response.
  • Geographically dispersed servers will make pages load faster by minimizing congestion and reducing unmanageable levels of traffic flow.
  • CDNs typically host static content including images, embedded objects, videos, media files and advertising for dynamic web contents. (for example: Yahoo!'s US audiences will get image pa-icons2.gif from http://us.i1.yimg.com/us.yimg.com/i/ww/t7/pa-icons2.gif while Australian audiences will get same image from http://au.i1.yimg.com/us.yimg.com/i/ww/t7/pa-icons2.gif.

9. AJAX:

  • All precautions for JavaScripts are also true for AJAX libraries. Try to utilize contents from Cache as much possible.
  • Load JavaScript libraries dynamically when required ($import()) or load in background with some delay.
  • Instead of getting 3rd party content on Server side, if possible, load third party content from Client side after displaying YOUR contents.

10. Other/Misc:

  • Using Server Side Include files are better as server keeps them in Cache to serve faster later.
  • Avoid "expression()" in CSS.
  • Move big developer comment/remarks into separate file of same name with *.info extension. e.g.: index.info
  • Trim URLs to short as possible. Use <base href="http://www.domainname.com"> if absolute referencing required.
  • IMPORTANT!: Align these guidelines for: (All quantitative analysis may differ in different environment)
    • Your environment and web structure.
    • Home page vs Interior page.
    • First Time Visitor vs Repeat Visitor.
    • High-Traffic page vs Low-Traffic page.
    • Byte Matters: few guidelines will save bytes while other will save kilobytes.
  • and finally, Measure your improvements.

Summary:

.HTML..........Simplify design.
  .HEAD
    .LINK......CSS file(s) required for page appearance.
    .SCRIPT....JS functions required during page load.
  .BODY
    ...........Small chunks (DIVs, TABLEs), minimize images.
    .SCRIPT....JS functions required after page load, validation etc.
    .PRELOAD...If required, Pre load any images here.

SECTION C: Tools

Footnotes

Some experts claim, If your home page does not load within 8 seconds, as much as a third of your site visitors will get frustrated and leave. I hope that these guidelines and examples would help to quickly understand and apply improvements to your web development.

Resources and further readings:

History

Lasted Updated: Monday, May 26, 2008.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Assad Baig
President Mashal Software, Inc.
Canada Canada
Assad Baig has been in Software Development since 1997, working for various Health Organizations, Media and Research Companies. Mainly worked on Microsoft Technologies and Development tools. He holds M.sc in Computer Science and MCSD.

Comments and Discussions

 
GeneralMy vote of 5 PinmemberAmir Mehrabi-Jorshary2-May-12 2:02 
GeneralMy vote of 5 PinmvpKunal_Chowdhury22-Apr-11 21:38 
GeneralMy vote of 5 Pinmemberthatraja10-Aug-10 22:53 
GeneralWell done PinmemberAbhishek Sur23-Dec-09 21:44 
GeneralExcellent PinmemberAarti Srivastava5-Feb-09 0:53 
Generalo.k. Pinmemberykorotia28-Nov-08 8:16 
General[Message Removed] PinmemberKatekortez25-Oct-08 9:29 
GeneralExcellent Article! Meaningful, Clear and Useful PinmemberMember 99284817-Aug-08 4:26 
QuestionI can publish? PinmemberWeder Lima30-Jun-08 2:42 
AnswerRe: I can publish? PinmemberAssad Baig30-Jun-08 3:10 
Generalvisit funscrape.com Pinmemberarbaz19-Jun-08 23:28 
GeneralWell done PinmemberMember 395829114-Jun-08 23:10 
GeneralGood Basic Info PinmemberMember 44845207-Jun-08 3:32 
AnswerRe: Good Basic Info PinmemberAssad Baig7-Jun-08 13:52 
GeneralGreat article PinmemberRalph Willgoss5-Jun-08 3:21 
Generali'd like to say great, but... PinmemberTerrential3-Jun-08 10:10 
GeneralEXCELLENT..good advice for the less experienced..like me..BUT I'm using IIS 5.0 Pinmemberbgriffin_tpa3-Jun-08 9:44 
GeneralGREAT PinmemberIslam ElDemery3-Jun-08 0:24 
GeneralVery nice Pinmembernmk_poy2-Jun-08 18:05 
GeneralVery nice Pinmemberxxx7862-Jun-08 16:46 
GeneralThe KING! Pinmemberadmirm2-Jun-08 9:56 
GeneralExcellent article! Pinmemberazamsharp31-May-08 12:53 
GeneralVoting PinmemberKamarey28-May-08 20:46 
GeneralGreat Post! I would just like to add... PinmemberCCMint28-May-08 16:39 
GeneralFantastic PinmemberJimBob SquarePants28-May-08 15:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140814.1 | Last Updated 26 May 2008
Article Copyright 2008 by Assad Baig
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid