- 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.
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.
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?
- Minimize the number of files (CSS, JS, IMAGES etc).
- 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)
- 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?
- 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.
- Faster Rendering:
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?
- Minimize the use of images.
- Use CSS rollovers instead of Images in links. (See example RollOvers.html in AllInOne.zip)
- Always specify
WIDTH
and HEIGHT
parameters for all IMG
. Even for smallest ones. - 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. - Avoid ANIMATED gifs and FLASH (because of long loading time and creates distractions.)
- Use background colors, fills and images (with repetition) instead of big images.
- Never keep identical images in more than one folder on server. (To avoid two HTTP requests and not getting benefit of first Cached image.)
- Load large images in layers/Progressive. Its tricky, try if works, may take longer but user may feel better.
- 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:
- 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?
- 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. - Minification: Remove space, newline, tab, comments; shorter strings, variables and literals; remove duplicate script and use CSS inheritance as much possible.
- 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.