Speeding Up By Being Lazy

Now that I've got my site redesign up and running, I've been making some small tweaks here and there and trying to improve performance where I can (the Yahoo Exceptional Performance team has a solid list of recommendations).

When someone hits my site for the first time (with no cached assets), the site can be a little slow to render any content. I'm using TypeKit for all of the fonts and it takes some time to pull down all of the encoded font data from their servers. I've chosen to hide all of the content on the page (except for the background image) until the TypeKit fonts are loaded to avoid the annoying flash of text restyling.

The site is just a single page and there's a lot going on, but since I want the page to feel like it's rendering more quickly, I need to minimize the number of assets that try to load at the same time as the TypeKit fonts. I already defer the loading of the portfolio thumbnails until TypeKit is finished, but there are still other images trying to load at the same time.

My strategy here was to take a page out of Flickr's playbook and lazy load the non-essential images until the critical items have finished loading. Flickr uses HTML5 custom data attributes for these types of images. 

Then they can loop through all of the elements with a data-defer-src attribute and set the src attribute to be the same. It's important to include width and height attributes to the images so that the renderer can allocate proper space for them to avoid layout shifting once the images do load.

Here's the Javascript I'm using to do this simple operation (it's MooTools-specific, but could be trivially ported to pure JS or any other framework):

The same concept could be applied to CSS background images as well. I plan on doing this next once I combine a bunch of images into a sprite to reduce HTTP requests.

Related: see Paul Hammond's article on 24ways.org about this technique.

Update: added note about image width and height attributes.

Clicky