How to use jQuery LazyLoad

One of the more popular way of loading images these days is jQuery LazyLoad. Essentially, this means not loading the image until the image is visible on the screen, or until a specified point on the page with relation to the image is scrolled to. There are some nice advantages, both aesthetically and performance-wise for using lazyload.

Aesthetically, it looks cool and modern. Performance-wise, if you are on a page with a lot of images they will not be loaded until the user scrolls, so the initial page load time will decrease.

Upload the javascript file to your child theme

Upload the file linked below to your child theme. In this example I am using a folder called ‘js’ (create if needed).

Gist Version
Grab from plugin page

Properly Enqueue the file

Add the snippet below to your functions.php file to properly enqueue the file. Learn more about enqueueing scrips here.

// Enqueue jQuery Lazyload
add_action( 'wp_enqueue_scripts', 'wd_enqueue_lazyload' );
function wd_enqueue_lazyload() {
     wp_enqueue_script( 'jquery-lazyload', get_stylesheet_directory_uri() . '/js/jquery.lazyload.js', array('jquery'), '1.9.3', true );
}

Update your image tags

First you must choose a class to add to all images you’d like to apply lazyload to. In this example I will use the class ‘lazy’. Second, instead of using src=”imageurl” you will use data-original=”imageurl” in the tag. See example below:

<img class="lazy" data-original="urltoimagehere">

If you’d like to have a placeholder image in place prior to the image loading you can add a src attribute:

<img class="lazy" data-original="urltoimagehere" src="placeholderimgurl">

Enable LazyLoad on all images with ‘Lazy’ class

The last step is to trigger the lazyload to work on all images with the specified class from the last stop. To do so simply add this snippet to any pages you need to use lazyload on. You can typically add this in the header.php if you want to use this script sitewide, or in specific page template files if it is only needed in certain areas of the site.

<script>
jQuery(document).ready(function() {
  jQuery('.lazy').lazyload();
});
</script>

There are other helpful tips such as using effects, click-triggering, image fallbacks and more found directly on the plugin page.

Comments

  1. Great stuff! I learned so much from this article. Thanks for the helpful tips! I have been looking for a way to do this, because loading the big long page of scrolling information was taking way WAY too much time! Thanks again!!! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *