In my previous post, The Quest For Speed, I mentioned that lazy-loading avatars is a good way to improve your site performance:
The overwhelming majority of visitors never leave a comment. Chances are, most don’t even scroll down to the comments section. So why waste their time and bandwidth by loading avatars that they’ll never see? A better option is to delay the loading of avatars until the user has scrolled far enough to actually see them.
I also promised to post the plugin that would allow you to implement this feature on your own WordPress site. So here it is.
lazy-avatars.zip (3 KB)
- Install and activate the plugin.
- Open your comments.php find a line that looks like this:
<?php wp_list_comments(); ?>
- Add this line above the wp_list_comments call:
<?php do_action('enable_lazy_avatars', true); ?>
This will enable the lazy-load feature for the avatar images in your comments section. If you want to use it everywhere on your site – e.g. in the sidebar or the admin panel – you can instead add the line from step #3 to your functions.php file.
The way it works is that the plugin replaces all avatar images with place-holder <div>’s. Then it monitors the scrollbar position. When one of the place-holders comes into view, the plugin creates a new <img> tag inside the place-holder <div> and sets its “src” attribute to the original avatar URL.
With regards to styling, each place-holder has any CSS classes that the original avatar image had, plus two more – “lazy-avatar” and “pending”. The “pending” class is removed once the avatar has been loaded. You can use this to apply a custom style to avatars that haven’t been loaded yet, e.g. a by adding a spinning “loading…” icon as the background image.
The plugin has been tested in the following environments:
- WordPress 3.0.4 and 3.1-RC2.
- Firefox 3.6, Opera 11, Chrome 9 and Internet Explorer 9.
It will probably work fine in older versions of Firefox, Opera, Chrome and possibly Safari (not tested). However, it will not work in any version of Internet Explorer older than IE9. This is because old versions of IE don’t support the addEventListener method and the pageYOffset property.
If you’d like to write your own image lazy-loading script that is fully cross-browser compatible, take a look at jQuery’s scroll and scrollTop methods. There’s also an inView jQuery plugin that could simplify the task even further.
The plugin also uses custom data- attributes to store avatar image URLs. This is, strictly speaking, not a standards-compliant thing to do (except in HTML5), but I’ve found that it works well enough in practice.Related posts :