HTML5, CSS3, jQuery, JSON, Responsive Design...

Rocket your website speed with CSS sprites!

Michael Brown   May 3 2014 04:37:23 AM
Here's two not very interesting web pages that show the national flags for various countries:

At first glance. they look identical.  But did you notice how much faster the second one loads up?  For me at least, the second one loads pretty well instantaneously, whereas the first is so slow that I can actually see the individual flags slotting into place.

The difference?  The first page uses bog-standard html img tags, whereas the second uses a CSS sprits.  So, the first page has to load 248 images.  The second loads only one, combined image (the sprite), and then uses CSS to display the correct part of that one image (i.e. the individual flags) over 248 div tags.

When measured, the speed difference is a wee bit special.  For me, Google Chrome reports that that the img tag version loads up in 2.96 seconds, whereas the CSS sprite version takes only 631ms.  Yep, that's a 469% speed increase!!

Why such a difference?

When trying to increase page load speeds, Web developers quite rightly zero in on the size of their elements - smaller equals faster, after all.  But just as important is trying to decrease the number of connections that a page has to make to load up its constituent elements.  All those those individual image file loads have to go through the entire connection/hand-shaking routine before the download actually starts.  There's also limits on the number of concurrent downloads a browser will allow from a single server.  This seems to be six concurrent downloads for most browsers, although for IE 8 and below it's only two.

Things get a little more complicated if you should need to resize the sprite-based images responsively, however.  And that will be the subject of a future post...

Note: I borrowed this bit of AppleScript from a StackOverflow post , in order to generate the HTML img tags for the first version of the flags page:
-- select multiple files, limited to images
set filelist to choose file of type "public.image" with multiple selections allowed

set html to ""

-- make a loop that goes through each file
repeat with imagefile in filelist
tell application "Image Events"
  set img to open imagefile
  -- get dimensions of image
  copy the dimensions of img to {W, H}
  -- build / concatenate html string
  set html to html & "[img alt=\"\" src=\"" & name of imagefile & "\" width=\"" & W & "\" height=\"" & H & "\" /]
  close img
end tell
end repeat

set the clipboard to html
display dialog "html for " & length of filelist & " images copied to the clipboard!"


(I changed the angled brackets to square ones to prevent the code from parsing on this page.)

To combine the flag images into the single image for the sprites, I used  This site also generates all your HTML and CSS automatically as it combines your source images into the sprite.

No Comments Found