Click here to Skip to main content
15,867,568 members
Articles / Web Development / XHTML
Article

Speed Up Your Website - By Example

Rate me:
Please Sign up or sign in to vote.
4.89/5 (95 votes)
26 May 2008CPOL13 min read 170.5K   986   245   30
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:
          Image 7
        • 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:
      GIFJPEG
      Quality: 10%
      JPEG
      Quality: 60%
      JPEG
      Quality: 100%
      Image 8
      Bytes: 156
      Image 9
      Bytes: 379
      Image 10
      Bytes: 433
      Image 11
      Bytes: 434
      Image 12
      Colors: 2
      Bytes: 318
      Image 13

      Bytes: 927
      Image 14

      Bytes: 1,994
      Image 15

      Bytes: 4,037
      Image 16
      Colors: 17
      Bytes: 713
      Image 17

      Bytes: 987
      Image 18

      Bytes: 2,159
      Image 19

      Bytes: 4,928
      Image 20
      Colors: 3+1 (transparent)
      Bytes: 379
      Image 21


      Bytes: 1,249
      Image 22


      Bytes: 2,823
      Image 23


      Bytes: 6,651


      When to use JPEG examples below:
      GIFJPEG
      Quality: 10%
      JPEG
      Quality: 60%
      JPEG
      Quality: 100%
      Image 24
      Colors: 256
      Bytes: 8,693
      Image 25
      [x]
      Bytes: 4,370
      Image 26
      Colors: 256
      Bytes: 6,952
      Image 27

      Bytes: 863
      Image 28

      Bytes: 1,962
      Image 29
      [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:
      Image 30
      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)


Written By
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

 
QuestionMy Vote 5 Pin
Dharmesh .S. Patil18-Jun-15 18:58
professionalDharmesh .S. Patil18-Jun-15 18:58 
GeneralMy vote of 5 Pin
Amir Mehrabi-Jorshari2-May-12 2:02
Amir Mehrabi-Jorshari2-May-12 2:02 
GeneralMy vote of 5 Pin
Kunal Chowdhury «IN»22-Apr-11 21:38
professionalKunal Chowdhury «IN»22-Apr-11 21:38 
GeneralMy vote of 5 Pin
thatraja10-Aug-10 22:53
professionalthatraja10-Aug-10 22:53 
GeneralWell done Pin
Abhishek Sur23-Dec-09 21:44
professionalAbhishek Sur23-Dec-09 21:44 
GeneralExcellent Pin
Aarti Srivastava5-Feb-09 0:53
Aarti Srivastava5-Feb-09 0:53 
Generalo.k. Pin
noname-201328-Nov-08 8:16
noname-201328-Nov-08 8:16 
GeneralExcellent Article! Meaningful, Clear and Useful Pin
skfaheem, Member 99284817-Aug-08 4:26
skfaheem, Member 99284817-Aug-08 4:26 
QuestionI can publish? Pin
Weder Lima30-Jun-08 2:42
Weder Lima30-Jun-08 2:42 
AnswerRe: I can publish? Pin
Assad Baig30-Jun-08 3:10
Assad Baig30-Jun-08 3:10 
Generalvisit funscrape.com Pin
arbaz19-Jun-08 23:28
arbaz19-Jun-08 23:28 
GeneralWell done Pin
DuneStart14-Jun-08 23:10
DuneStart14-Jun-08 23:10 
GeneralGood Basic Info Pin
dpminusa7-Jun-08 3:32
dpminusa7-Jun-08 3:32 
AnswerRe: Good Basic Info Pin
Assad Baig7-Jun-08 13:52
Assad Baig7-Jun-08 13:52 
GeneralGreat article Pin
Ralph Willgoss5-Jun-08 3:21
Ralph Willgoss5-Jun-08 3:21 
Generali'd like to say great, but... Pin
Terry Kernan3-Jun-08 10:10
professionalTerry Kernan3-Jun-08 10:10 
GeneralEXCELLENT..good advice for the less experienced..like me..BUT I'm using IIS 5.0 Pin
bgriffin_tpa3-Jun-08 9:44
bgriffin_tpa3-Jun-08 9:44 
GeneralGREAT Pin
Islam ElDemery3-Jun-08 0:24
Islam ElDemery3-Jun-08 0:24 
GeneralVery nice Pin
nmk_poy2-Jun-08 18:05
nmk_poy2-Jun-08 18:05 
GeneralVery nice Pin
xxx7862-Jun-08 16:46
xxx7862-Jun-08 16:46 
GeneralThe KING! Pin
admirm2-Jun-08 9:56
admirm2-Jun-08 9:56 
GeneralExcellent article! Pin
azamsharp31-May-08 12:53
azamsharp31-May-08 12:53 
GeneralVoting Pin
Kamarey28-May-08 20:46
Kamarey28-May-08 20:46 
GeneralGreat Post! I would just like to add... Pin
CCMint28-May-08 16:39
CCMint28-May-08 16:39 
GeneralFantastic Pin
JimBob SquarePants28-May-08 15:04
JimBob SquarePants28-May-08 15:04 

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

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