File Under: Backend, UI/UX

Site Optimization Tutorial – Lesson 1

A picture’s worth a thousand words. An old saying, but true enough on the web where you can transfer chapters of text in the time it takes to download just one big image. Ever notice how pictures are always the last thing to show up when you’re surfing? That’s because the biggest hunk of download time comes from the image files.

Over the next four days, we’ll be looking at all the different ways to get pages down to their leanest and meanest. Today we start with the most egregious and most obvious culprit: images.

By the way, a lot has changed since the first edition of this tutorial – there’s more to optimizing image performance today than just knowing your GIFs from your JPEGs. (Though we’ll review that, since this may be your first time around.) There are now other file formats (like PNG) worth considering, and improved weighted-optimization techniques to throw into the mix.

And, hey, quite a bit hasn’t changed. For one, web users haven’t gotten any more patient. It doesn’t matter how ice-cool your images may look – if they can’t be downloaded quickly over a 56K modem, very few people without broadband will stick around to see them.

Fortunately, there’s still a host of tricks and optimizations that web designers can implement to speed image downloads. Let’s start with the easiest thing in the world.

Contents

  1. Don’t Need It? Don’t Use It.
  2. Image Formats
  3. JPG and PNG Basics
  4. Standard Image Compression
  5. Advanced Compression Techniques
  6. Faster Than a Speeding Progressive Download
  7. Cache Is Your Friend
  8. Size ‘Em Right

Don’t Need It? Don’t Use It.

Nothing tricky or techie about this, but, friend, it works wonders. Before you do anything else, remove every superfluous image from your page’s design. Now “superfluous” doesn’t mean your company logo or a useful map to your office. We’re talking about that clever, animated envelope next to your Send Mail link. Or, if your site has a splash page with a big logo and a [CLICK HERE TO ENTER!] link, ditch it and send your audience directly your main page. Trust us:a fast-loading, functional website gives your business a better image than some splashy intro that offers the user no real content, and nothing to do but wait for the next page to load.

Remember, shaving a paltry 10KB image off your site may not sound like that impressive an improvement, but if you’re working with a 40KB page, that 10 KB represents a healthy 25 percent reduction in download time not a bad trade for the loss of hi-res picture of your new Hello Kitty toaster.

If you’re really hell bent about creating split-second page loads or you have a page that desperately needs trimming, consider axing graphical submit buttons and replacing them with text submits. They are recommended by user interface experts and users alike.

Click to Submit Data

Also, you can replace animated GIFs with static images, which take a fraction of the time to download.

Finally, a lot of fancy “header” and navigation graphics can be replaced with larger text, appropriately styled with a tag or CSS. These days, this option works better than ever, because Windows XP and Mac OS X browsers natively support text anti-aliasing. This process smooths the jagged edges around fonts, giving screen type a more natural, refined look, especially at bigger font sizes.

Image Formats

Unless you’re bent on evoking that retro-fly ARCHIE or GOPHER feel, you’re probably going to be using some images on your pages. Just follow a few simple guidelines as you generate your images, and your pages will download in record time.

To begin with, decide whether a given image ought to be a GIF, JPEG, or PNG. This may seem elementary, but it’s a mistake that’s still slowing down a good percentage of web pages out there.

GIF is the oldest and most compatible file format for pictures on the web perfectly suited for smaller graphics that need to look crisp and clean, but don’t need more than 256 colors. GIFs can also be saved with one “transparent color,” allowing them to have irregularly shaped borders. Simple company logos, icons, and navigation buttons are good examples of graphics that should be saved in GIF format.

Now, PNG is a lot like GIF – in fact, it was developed to be a patent-free alternative to GIF, created with the same sort of uses in mind. PNG builds on GIF’s basic features, with improvements like more colors, fancy multilevel transparency (ideal for delicate drop-shadow effects), even gamma-correction, which ensures that colors look the same on Mac, Windows, and Linux computers. Best of all, not only are PNGs just as good as GIFs in almost every way, but PNGs use better file compression so they’re smaller files which load more quickly.

In short, PNG is an excellent substitute for GIF, built to handle the same types of graphics (logos, icons, irregularly-shaped items, et cetera) better and faster. There’s just one BIG drawback:a tiny, tiny percentage of browsers won’t display PNGs at all! And, because of this, hardly anybody uses PNGs yet.

So should you risk stepping up to PNG just to make your pages faster? Well, probably, “Yeah!” We’ll come back to that decision, but first, let’s talk compression basics, and see how underdog PNG and old-timer GIF stack up against JPEG, the hulking file format that crushes photo-realistic data into teensy-weensy files.

JPG and PNG Basics

PNGs and GIFs use a lossless compression format. Unlike a JPEG, the details of your graphic won’t get blurry. If you’re scanning something like a finely detailed map, or creating anything with small text, you should choose the GIF or PNG format. Just keep in mind that using GIFs (and even PNGs) for large pictures leads to huge file sizes and long download times.

For example, take a look at these three images:

siteoptimization1_mapgif.gif 12 KB GIF

siteoptimization1_mappng.png 13 KB PNG

siteoptimization1_mapjpg.jpg 12 KB JPG

The first is a GIF, the second is a PNG, and the third is a JPEG. All three files are comparable size-wise, right around 12K. If this were a map to your office, which two formats would you consider? Right. So why use JPEGs at all, then?

Well, take a look at these three images:

siteoptimization1_cactusgif.gif 49 KB GIF

siteoptimization1_cactuspng.png 44 KB PNG

siteoptimization1_cactusjpg.jpg 12 KB JPG

Again, the first is a GIF. Even though it’s maxing out at 256 colors (it’s 8-bit), it looks OK, but you’ll notice that the file size is huge. The second is a picture-perfect PNG, displaying thousands of colors at once, so the shading between similar colors is really nice and smooth. But again with the big file size.

Now the third file, a JPEG, is also using thousands of colors, and lookin’ pretty good, too. And check out the small, superslim file size! See, JPEG has the advantage of “lossy” compression in which some information is actually discarded when creating the file. So while you might see some photographic details being blurred, and other tell-tale digital artifacts that are the bi-product of lossy compression, the overall image looks OK, and the file size is a fraction of what can be achieved with more accurate lossless methods.

JPEGs are the perfect file format for color photographs on the web, whether they’re scanned or straight from the digital camera. Just keep in mind that JPEGs can’t do animation or transparency, and they don’t handle detailed drawings as well as GIFs or PNGs.

Standard Image Compression

Grab a demo of GraphicConverter, Photoshop, or Fireworks and experiment with compression. Try a bunch of different settings and see what you liked best in terms of display quality and file size.

JPEG offers the widest range of compression levels, technically speaking, but it’s pretty intuitive: The more you compress an image, the worse it looks. Image-editing programs generally offer Low, Medium, and High options for image quality. Photoshop and Fireworks let the user twist the compression dial anywhere between levels 1 and 100. (Yes, and Nigel Tufnel would be impressed – but may we suggest a level 101?) Avoid the extremes, obviously, but determining the right level of compression on a given photograph is ultimately up to you.

You can’t variably compress GIFs or PNGs per se, but you are able to reduce their color bit depth, which limits the number of colors used. To calculate the number of colors at a given bit depth, take 2 to the power of the bit depth (i.e., 8-bit color = 256 colors). The fewer the colors, the smaller the kilobyte size of the image. Say you’re building the Coca-Cola website – you can probably reduce your logo to a bit depth of 2 or 3. 2-bit color allows you a bold red and a white, but 3-bits buys you a few extra shades of each to smooth out rough edges. Speaking of extra shades, optimization pros will notice that using anti-aliased text in graphics makes it much harder to lower image bit depths. The anti-aliasing effect requires many extra colors to give text that softer look. If you must use type in your images, keeping it plain helps shrink file sizes and makes the text easier to read.

siteoptimization1_flowerpot4.gif

siteoptimization1_flowerpot256.gif

Above: 2-bit and 8-bit versions of the same image. If you don’t need an extended range of colors, there’s no need to use higher bit depths!

Advanced Compression Techniques

Even the simplest image-editing utilities let you play around with bit-depths and other compression settings. Photoshop offers a superb interface for previewing and managing compression options. Controlling color tables, dithering, and transparency while you fine-tune an image’s size is a breeze with these two titles.

Photoshop has other options for power-users wanting better control over the image compression process. With weighted optimization, you identify important areas in your image using a masking tool, and then vary the compression settings across the image’s different regions. For example, you could apply maximum compression to the background of a candid snapshot, and apply better image quality to the people in front. Your finished product shows people’s faces without any strange-looking digital artifacts, while the unremarkable background contains evidence of higher compression settings.

Weighted optimization works on GIFs, too. For instance, you might mark off key aspects of logo artwork, so critical image areas wouldn’t dither or have colors jump, when you began adjusting the bit depth.

Nifty, eh? Well, to quote every self-respecting TV infomercial, “Wait! That’s not all!” There are other Ginsu-sharp tools in Photoshop’s “Save For Web” dialog. One is a blur effect for JPEGs that reduces the impact of digital artifacts – most handy, but best used with a light touch. Photoshop also lets you specify JPEGs to be formatted as “Baseline Optimized”, which is a slightly smaller format file size-wise. Disregard Photoshop’s warning that Baseline Optimized JPEGs are less compatible – they look OK in all browsers. Well, except of course for Lynx.

<nerd> (Alright, alright. Since you really want to know, baseline optimized images use different quantization divisor tables and Huffman dictionaries than specified in the old-school JPEG/JFIF standard. So while optimized images may throw some image-editors and encoding software for a loop, the JPEG decoder in a web browser doesn’t care, since it parses the DQT and DHK markers to get those tables! Yeah, like, I know, how wacky is that?) </nerd>

Obviously, JPEG compression relies on extremely advanced mathematics. GIFs on the other hand…

A GIF is just a list of colored pixels. GIF’s only attempt at compression is to abbreviate whenever same-color pixels are right next to each other horizontally. And that’s all.

So with a row of 100 white pixels, the GIF format saves space by using an annotation along the lines of “one white, 99 more of same color”. A row of alternating black-and-white pixels, on the other hand, requires a more verbose description (“one black, one white, one black, one white”) and soaks up more space. Basically, it’s a big deal if colors change on the same horizontal line.

Photoshop does have a “Lossiness” feature for decreasing GIF sizes, which takes advantage of GIF’s fondness for like-color clumps. Photoshop will substitute pixels here and there, and try to increase the number of same-color pixels sitting next to each other. It works okay, but not as well as it sounds; the automated results can look pretty bad, especially on the types of pixel-perfect artwork you’d want to use GIF for, anyway.

If you’re hell-bent on optimizing a GIF’s size beyond reducing its colors, consider the compression scheme while designing it, and avoid changing colors along the horizontal axis. E.G., if you were drawing a logo with a “black-white-black-white” checker pattern in parts, consider using a solid grey instead. Don’t forget, GIF compression only takes horizontal rows into account. Ten vertical lines of white pixels occupy as much space as ten vertical lines of ten different colors.

siteoptimization1_badgif.gif Bad GIF pattern

siteoptimization1_goodgif.gif Good GIF pattern

Wow! I think we finally have compression covered.

Executed by an expert (that’s you now!), this increased control over image optimization should squeeze a few more kilobytes from each of your images, saving users seconds (and hopefully minutes) when paging through your site. That’s charitable, but remember:when a user doesn’t feel their time is being wasted, they’re liable to do just that – waste serious time. When they do it at your site, clicking link after link, that’s a good thing.

Faster Than a Speeding Progressive Download

Alright. So your images are now as small and fast they can get. Let’s quickly cover one way to make them seem faster without focusing on file sizes.

When you save images in an “Interlaced” (GIFs and PNGs) or “Progressive Loading” (JPG) format, the browser displays your pictures as fast as they can. First, they draw a rough approximation of the picture, then fill in details later. Sloppy as it sounds, this improves the user experience, because basic page elements get assembled quickly. Users can interact with the page – read your text content and such – before the loading process is completely finished.

In the mid-90′s Paleoithic Era of the web, designers used the “lowsrc” attribute of the <img> tag for similar reasons. Browsers can load a super-compressed version of an image first, then load the “real” file later. The lowsrc approach – which requires downloading twice as many images – has been all but abandoned in favor of the progressive-loading technique.

If you’re slipping into the radical optimization mindset, you’ve no doubt noticed that progressive or interlaced images are sometimes a little bigger kilobyte-wise. In this case, learn to live with it – there’s more to making a page “optimized” than just download size.

In fact, there are 3 kinds of speed to think about on the web:

  • Download Speed
  • Render Speed
  • Visual Accessibility

A user makes the split-second decision between clicking through or heading back based upon a combination of these three types of speed. A good designer needs to find a way to balance the three elements, not unlike balancing a house of cards, to create the ideal download.

Note that this timeline ends the first second a visitor is able to access and meaningfully interact with a page, not strictly when the page finishes rendering. In terms of user experience, rendering time is often academic.

Knowing when a page has rendered enough to be useful (as opposed to a concrete ceiling of 10 KB or a “no more than three graphics per page” rule) gives a designer the layout latitude necessary to create a successful page. As long as users don’t ask, “Hey, how big is this page, anyway?”, the page is doing its job.

Cache Is Your Friend

There’s one more important technique that’s key to boosting the perceived speed of your site. Those images that repeat throughout your site – common logos, headers, or navigation bars – don’t need to be downloaded more than once. By default, most browsers set aside a memory cache to store recently-used images in RAM and on the hard disk. If a browser recognizes the same filename, it’ll pull the image straight from the cache instead of downloading it. This provides a massive performance boost that a lot of automated timing programs don’t acknowledge. Just pull out a stopwatch and see for yourself.

Since the client-side cache is such a useful ally, you should design pages with the browser cache in mind. For instance, if your site uses a number of different header graphics that vary only slightly (like a standard logo with various department names underneath it), try breaking up the image so that the unchanged portion (the standard logo) is stored in the cache and always loads immediately. Though you’ll still need to load a new graphic on each page (in this case, a department name), the image is smaller and therefore downloads faster.

Browser caches are conceptually similar, but not the same thing as Network (or “Proxy”) cache, which we cover later in this Tutorial.

Size ‘Em Right

While your image editor is open, make sure the image is the same size (at 72 dpi) as it will appear on the web page. In your HTML, use the WIDTH and HEIGHT attributes of the  IMAGE¢ tag to restate the image’s actual dimensions. This allows the browser to lay out the rest of the page while the image is still downloading – so folks have something to read while they wait – and ensures that people surfing with “images off” will still see the page in its proper layout.

If you’re using tables on your page, image dimensions take on a special importance since dimensionless images sometimes force browsers to clear and re-render the page. This occurs when a browser starts building the table’s structure according to the HTML-specified <TABLE> and <TD> dimensions and then, belatedly, discovers that an image lacking HTML dimensions is, in fact, too large to fit. Browsers will then re-render the table to accommodate the unwieldy image. This inefficient page rendering takes time, and it’s unpleasant for the user to see page elements move around, or disappear and reappear.

You probably know this already, but when it comes to the WIDTH and HEIGHT attributes, the most important thing to remember is never use them to re-size or adjust the shape of graphics on your pages! Re-sizing via HTML is super-bad for two reasons. First, if you increase an image’s dimensions larger than the image’s actual size (at 72 dpi), you’ll end up with a jagged picture. Like this:

siteoptimization1_imagesix.gif

Secondly, you’ll take a nasty performance hit. Using HTML to make an image appear smaller than its true size doesn’t always look as bad, but much more data gets downloaded than the browser actually needs for drawing the image, thus adding to the download time.

Rules, of course, are made to be broken, and there is one case where it’s acceptable to fracture this rule. If you’ve been browsing Wired and Webmonkey long enough, you’ve probably seen images like this:

siteoptimization1_imageseven.gif siteoptimization1_imageseven.gif

In this case, both pictures are actually the same GIF file, so they take the exact same amount of time to download. However, the one on the right has been doubled in size via the WIDTH and HEIGHT attributes of the img tag. There isn’t any jaggedness because this image lacks any curves or diagonal lines. If you’ve got a logo or design that’s all right angles (lucky dog), you can use a super-small GIF (which downloads cheetah-quick) and then re-size it to your heart’s content in HTML – just remember to keep the dimensions proportional.

You artsy folks out there might want to experiment with using HTML to re-size all sorts of images for creative effect (certainly the designers here at Wired used to enjoy it). Of course, only you know if the company president will care if you take the “artsy approach” with his photo.