Artificial Intelligence

Improved Lazy Loading for iPhone & Android

The latest version of the jQuery Lazy Load plu


The latest version of the jQuery Lazy Load plugin (released Jan 29th, 2012) included the ability to customize your data attribute parameter. This is a pretty helpful update; I realized it could be used to set multiple source images for the same node. Here's how you can use it to optimize images, cutting down on data transfer for mobile devices.

Set up your lazy loading the normal way - generally this is gives you HTML like this:


A cute kitten

The data-original attribute specifies the actual source of your lazy load image. The javascript to complement then looks something like this:


$('img')
.lazyload({
effect : 'fadeIn'
});

Now your lazy loading should be working, if your scripts are included in your page and everything is set up correctly. However, if your site features very large images and you have a responsive stylesheet set up, your readers can benefit from loading optimized images. I like to give a "width-full" class to any images that are full-width optimized. Then I hit that class in my media queries, hiding any .width-full content with display:none; . Because the lazy load script doesn't load hidden images by default, this prevents the script from loading on those images, saving readers the download time.

Now go back to your image tags, and specify the location for the optimized image in a data-mobile attribute. Something like this:


A cute kitten

You can add these changes to your template files when appropriate, so this is all done under the hood.

As it is, your lazy load should still be working the default way in all circumstances. A media query is how we will trigger something different to happen for mobile. With just a few lines of CSS:


@media only screen
and (max-width: 480px) {
.width-full {
display:none;
}
}

Now we add a few lines of jQuery to call out those images. We aren't targeting the class, we're targeting the visibility and the attribute. We only want the lazy load plugin to run the mobile version when the media query rules have hidden it, and only then if it has mobile optimized content. So after our initial lazy load, you can add this:


$('img:hidden[data-mobile]')
.attr('width','')
.attr('height','')
.show()
.lazyload({
effect : 'fadeIn',
data_attribute : 'mobile'
});

There's a few things going on here. First it resets the image height and width attributes so that your image loads without being distorted, then it shows the image, and runs the lazyload directly, using the data-mobile data_attribute parameter. If there's no mobile-optimized version, it will just keep the image hidden. You can cut down load times while making your content available in the right context.

Similar posts

Get notified on new marketing insights

Be the first to know about new B2B SaaS Marketing insights to build or refine your marketing function with the tools and knowledge of today’s industry.