Creative Services Toolkit

Tutorials

How to Lazy Load Images

This tutorial will teach you how to reducing the intial file download size of your creative by lazy loading images.

Purpose

The purpose of this tutorial is to teach you how to lazy load any imagery that is not initially visible when the creative is first loaded.

Why does it matter?

Over the past few years as we've begun to build HTML creatives, we've not been held to the tight file size restrictions that came with Flash. However, in the near future file size restrictions will again be imposed on us, as well as the total number of file requests a creative makes. In order to comply with these new guidelines we'll need to lazy load large files, especially images.

Determine which images should be lazy loaded

Any images that aren't initially visible in your creative should be lazy loaded. Things like:

  • Carousel images on secondary frames
  • Images that are not visible on load, but become visible later
  • Images in expanded content that is not visible until user interacts

The HTML

  • Create a new img tag to use as a placeholder for where the image will load later.
  • Set the src value to empty or #. This ensure the browser doesn't load anything.
  • Add a data-src attribute for the URL image.

The Javascript

  • The above Javascript code creates a function called loadImages, which you can then call whenever you want the images to load. Here's how it works:
    • 1. $("img[data-src]") finds all images that have the data-src attribute. These should be the images we want to lazy load.
    • 2. for.. creates a loop that processes each of the images that need to be lazy loaded.
    • 3. if(!el.hasClass("loaded")) creates an if statement that checks if the image has already been loaded or not.
    • 4. If it has not been loaded, take the data-src URL and update the src of the image. This triggers the browser to load the image.
    • 5. Finally Add class of loaded so later if we run the function again it will skip the images that are already loaded.
  • When you want to run the function simply call it with loadImage();

Examples

Load on mouseover

Load on mouseover with time threshold (mouseover for 1 second to trigger load)

Load when carousel goes to the next slide

Load when pushdown expands