Developer Network Home - Help

YUI 2: ImageLoader

YUI 2: ImageLoader

The ImageLoader Utility allows you as an implementer to delay the loading of images on your web page until such a time as your user is likely to see them. This can improve your overall pageload performance by deferring the loading of some images that are not immediately visible at the time the page first renders. Because images are often the heaviest components of a given page, deferring the loading of some images can yield a marked improvement in the way the page "feels" to your user.

The ImageLoader Utility lets you determine triggers and time limits to initiate image loading. This allows you to ensure that the images are loaded before your user is likely to see them. This technique, obviously, is appropriate only for images that are not immediately visible to your user at initial page load.

Getting Started

To use the ImageLoader Utility, include the following source files in your web page with the script tag:

  1. <!-- Dependencies -->
  2. <script src="https://yui-s.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
  3.  
  4. <!-- Source file -->
  5. <script src="https://yui-s.yahooapis.com/2.9.0/build/imageloader/imageloader-min.js"></script>
  6.  
<!-- Dependencies -->
<script src="https://yui-s.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
 
<!-- Source file -->
<script src="https://yui-s.yahooapis.com/2.9.0/build/imageloader/imageloader-min.js"></script>
 

YUI dependency configurator.

YUI Dependency Configurator:

Instead of copying and pasting the filepaths above, try letting the YUI dependency Configurator determine the optimal file list for your desired components; the Configurator uses YUI Loader to write out the full HTML for including the precise files you need for your implementation.

Note: If you wish to include this component via the YUI Loader, its module name is imageloader. (Click here for the full list of module names for YUI Loader.)

Where these files come from: The files included using the text above will be served from Yahoo! servers; see "Serving YUI Files from Yahoo!" for important information about this service. JavaScript files are minified, meaning that comments and white space have been removed to make them more efficient to download. To use the full, commented versions or the -debug versions of YUI JavaScript files, please download the library distribution and host the files on your own server.

Order matters: As is the case generally with JavaScript and CSS, order matters; these files should be included in the order specified above. If you include files in the wrong order, errors may result.

Creating an Image Group

Images are organized into groups. Each group has one or more triggers. A trigger is simply any DOM event, such as the mouseover of a specific <div>, a button click, or a window scroll. The images in a group won't load into the page until this trigger fires. Groups also have an optional time limit; if none of the group's triggers are activated before the time limit expires, the images are fetched anyway.

A group is defined as an instance of YAHOO.util.ImageLoader.group. It comprises a collection of images that will show up on the page based on the same triggers and time limit.

  1. var myFirstGroup = new YAHOO.util.ImageLoader.group('someDivId', 'mouseover', 2);
  2.  
var myFirstGroup = new YAHOO.util.ImageLoader.group('someDivId', 'mouseover', 2);
 

This defines a group triggered by a mouseover of the <div> with the HTML ID of someDivId; the third argument is the time limit, and in the code above we are specifying that all images in myFirstGroup should load two seconds after the window's load event fires even if our trigger hasn't been tripped.

Adding Images to the Group

Register one or more images with the group using the HTML ID of the image element and the URL for the image:

  1. myFirstGroup.registerBgImage('idOfDivWaitingForImage', 'http://www.example.com/image/url');
  2.  
myFirstGroup.registerBgImage('idOfDivWaitingForImage', 'http://www.example.com/image/url');
 

This will set the image at http://www.example.com/image/url as the background image of the <div> with the ID idOfDivWaitingForImage. There are three kinds of images you can register with an ImageLoader group instance; see Adding Images below for more details on this process.

Using ImageLoader

This section describes how to use the ImageLoader Utility in further detail. It contains these subsections:

Performance Considerations

The images on your page require possible DNS lookups, new HTTP transactions, and ultimately the transmission of image data in packets over the wire. While all this is happening, the user is often left waiting for the page to become fully functional. All of your onload JavaScript, for example, is deferred until after all the page's images have finished loading.

Should the user have to wait for all of these images? If the images are front and center on the page, then yes, suffering the load time is necessary. But what about images that the user doesn't see right away &mdash the images below the fold; the images hidden towards the end of a carousel; the images that won't appear until a non-default tab of some module is clicked? ImageLoader allows you to delay the load of these images until after page load so that the page is fully functional more quickly. And, by using triggers, you can ensure that the images are loaded just before the user needs them so that there's no degradation of user experience.

Approach

How can you anticipate when the user will be able to see images? Well, you as a developer know your page, and you know what actions are available to the user. You can utilize your knowledge to identify user events that indicate what the user is about to see.

For example, you know that any image lying below the fold won't be visible until the user either scrolls the page or resizes the browser window. In a tabbed module, you know that the user can't click one of the tabs until she mouses over that tab.

Consequently, you can use scroll events, mouseover events, or other indicators of user intent to stay one step ahead of the user and decide when to load images. The ImageLoader Utility lets you do exactly this.

Triggers

Images are grouped together in terms of which user action(s) should trigger their loading. A trigger is simply any DOM event. Your first step is to create an ImageLoader group object, with its trigger defined:

  1. var myFirstGroup = new YAHOO.util.ImageLoader.group('someDivId', 'mouseover', 2);
  2.  
var myFirstGroup = new YAHOO.util.ImageLoader.group('someDivId', 'mouseover', 2);
 

The third parameter is a time limit for the group. If the user has not performed the trigger event within the specified time limit, the images are fetched anyway. Either the time limit or the trigger may be null (indicating the user must perform the trigger event, or there should only be a simple time delay, respectively.)

You can have as many triggers as you wish for a group. Just add them with the group class's addTrigger method:

  1. myFirstGroup.addTrigger('someOtherDivId', 'click');
  2.  
myFirstGroup.addTrigger('someOtherDivId', 'click');
 

The trigger conditionals are disjunctive; the first one to fire initiates the image fetching.

Custom Event Triggers

You can also specify custom events as triggers. Call addCustomTrigger with any YAHOO.util.CustomEvent object:

  1. var myILEvent = new YAHOO.util.CustomEvent('anImageLoaderTrigger');
  2. myFirstGroup.addCustomTrigger(myILEvent);
  3.  
var myILEvent = new YAHOO.util.CustomEvent('anImageLoaderTrigger');
myFirstGroup.addCustomTrigger(myILEvent);
 

Adding Images

Once a group is created, you can add as many images as you'd like to it. There are three types of images:

  1. background image (a <div> with a background image; URL set in style.backgroundImage). Use the registerBgImage method to register this kind of image.
  2. source image (an <img> tag; URL set in a url attribute). Use the registerSrcImage method to register this kind of image.
  3. png background image (a <div> with a png background image; for IE6, sets an alpha filter src; for other browsers sets a background image). Use the registerPngBgImage method to register this kind of image.

To add an image to a group, register the DOM ID of the image element and the image URL:

  1. myFirstGroup.registerBgImage('idOfDivWaitingForImage', 'http://www.example.com/image/url');
  2. myFirstGroup.registerSrcImage('idOfImgWaitingForImage', 'http://www.example.com/other/image/url');
  3. myFirstGroup.registerPngBgImage('idOfDivWaitingForPngImage', 'http://www.example.com/png/image/url');
  4.  
myFirstGroup.registerBgImage('idOfDivWaitingForImage', 'http://www.example.com/image/url');
myFirstGroup.registerSrcImage('idOfImgWaitingForImage', 'http://www.example.com/other/image/url');
myFirstGroup.registerPngBgImage('idOfDivWaitingForPngImage', 'http://www.example.com/png/image/url');
 

This will set the image at http://www.example.com/image/url as the background-image of the <div> with the ID idOfDivWaitingForImage and likewise with the two other image elements.

Loading Images Below the Fold

A group can check its images during the window object's load event (or the Event Utility's onDOMReady event) and immediately begin loading those that are above the fold (i.e., inside the current viewport) while delaying the load of those that aren't. Just set the foldConditional property of the group to true. Usually the group will have window-scroll and window-resize triggers.

  1. var foldGroup = new YAHOO.util.ImageLoader.group(window, 'scroll', null);
  2. foldGroup.foldConditional = true;
  3. foldGroup.registerBgImage('partwayDownPageImage', 'http://www.example.com/image/url');
  4. foldGroup.addTrigger(window, 'resize');
  5.  
var foldGroup = new YAHOO.util.ImageLoader.group(window, 'scroll', null);
foldGroup.foldConditional = true;
foldGroup.registerBgImage('partwayDownPageImage', 'http://www.example.com/image/url');
foldGroup.addTrigger(window, 'resize');
 

Image Visibility

You can set your <img> tags to have the CSS property visibility:hidden. This will allow your page to keep its structure until the image is actually loaded. Since these images are probably out of the viewport anyway, this may not make a perceptible difference, but it will help some browsers avoid reflowing the page when deferred images are loaded. To accomplish this using ImageLoader, set the setVisible attribute of the image to true; ImageLoader will then set the visibility property to visible when the image is fetched.

  1. var someRegisteredImg = someGroup.registerSrcImage('someImgEl', 'http://www.example.com/image/url');
  2. someRegisteredImg.setVisible = true;
  3.  
var someRegisteredImg = someGroup.registerSrcImage('someImgEl', 'http://www.example.com/image/url');
someRegisteredImg.setVisible = true;
 

Using Class Names

As an alternative to registering each image with a group, you can use CSS class names to group images together. When using this approach, images that are part of the same group should all share a common class name. Each should also have its image set as the element's background image via CSS in the element's style attribute. To prevent the image from loading immediately when the element renders, create a CSS style definition for that class overriding the background image to none. Lastly, set the className property of the ImageLoader group.

The following combination of CSS, HTML, and JavaScript illustrates this approach:

  1. .yui-imgload-somegroup {
  2. background: none !important;
  3. }
  4.  
.yui-imgload-somegroup {
    background: none !important;
}
 
  1. <div class="yui-imgload-somegroup" style="background-image: url(http://www.example.com/image/url);"></div>
  2.  
<div class="yui-imgload-somegroup" style="background-image: url(http://www.example.com/image/url);"></div>
 
  1. someGroup.className = 'yui-imgload-somegroup';
  2.  
someGroup.className = 'yui-imgload-somegroup';
 

Important Usage Requirements

There are some important things to keep in mind while using the ImageLoader Utility. Otherwise it may not work the way you expect, or it may have some undesired side effects.

"src" Attribute of Source Images

When using ImageLoader with <img> elements (via the registerSrcImage method), leave the src attribute out of the HTML element altogether. Do not set an empty string for the value of src. Some browsers react to this by assuming the empty string means "/", and consequently the browser re-requests the current HTML page and tries to stuff it into the <img> element. This is bad news for performance.

<img id="anImgEl" />
<img id="anImgEl" src="" />

Resizing Images

When resizing <img> elements (via registerSrcImage method) on the fly (setting unnatural width and height attributes), the height and width of the image must be specified in the JavaScript. Do this by passing the width/height into the registerSrcImage call. Failure to do this will result in no resizing. Browsers ignore width/height set in the HTML when there is no src attribute. And when the src is finally set, the width/height end up being the image's natural size.

someGroup.registerSrcImage("someImgDiv", "http://www.example.com/image/url", W, H);
someGroup.registerSrcImage("someImgDiv", "http://www.example.com/image/url");

Support & Community

The YUI Library and related topics are discussed on the on the YUILibrary.com forums.

Also be sure to check out YUIBlog for updates and articles about the YUI Library written by the library's developers.

Filing Bugs & Feature Requests

The YUI Library's public bug tracking and feature request repositories are located on the YUILibrary.com site. Before filing new feature requests or bug reports, please review our reporting guidelines.

ImageLoader Utility Cheat Sheet:

Cheat Sheet for the Animation Utility.

Download full set of cheat sheets.

YUI Theater — Matt Mlinac: "The YUI ImageLoader Utility"

Yahoo! Engineer Matt Mlinac introduces you to the ImageLoader Utility.

9 minutes; source: Yahoo! Video (Flash) or download.yahoo.com (M4V, iPod/iPhone-compatible). Yahoo! Engineer Matt Mlinac introduces you to the YUI ImageLoader Utility.

YUI ImageLoader on del.icio.us:

bookmark on del.icio.us

be the first to bookmark this page!

Copyright © 2017 Yahoo! Inc. All rights reserved.

Privacy Policy - Copyright Policy - Job Openings