How to Add Lazy Loading to WordPress

How To Add Lazy Loading To WordPress

Lazy Loading is a front-end development trick which delays the loading of content below the fold of a page until just before a user scrolls to it. You can think of it as the opposite of image preloading. It ensures that resources, especially those that carry more weight (images, videos, scripts), are only loaded when they have to be. Lazy loading can be used in a variety of different ways. You can chose to sprinkle the technique on and delay the loading of a single resource, like images, or you can implement it full-scale for your entire site with infinite scroll. In this article, we’ll talk through what lazy loading is, then go over a few ways to implement it in WordPress.

The Pros and Cons of Lazy Loading

The biggest advantage of lazy loading your content is that it makes your initial page load quite a bit faster. If the browser doesn’t have to worry about loading in every resource on your page right away, it can load the content immediately visible to a user much quicker. As the user begins to scroll, content will be loaded in.

Often, lazy loading is referred to in discussions of infinite scroll. Infinite Scroll is really an alternative to pagination. It is a technique where new content is loaded in every time a user scrolls to the bottom of the page. You’ve probably seen it on the web somewhere, on blogs or sites like Pinterest. This makes content discovery a lot easier without readers having to click through page after page to find what they are looking for. It also saves you a page load when all you need to do is load in a few more posts for people to view. In the long run, and when implemented properly, lazy loading can make your site a lot faster and can be a really great experience for your users.

Pinterest infinite scroll

But lazy loading, and infinite scroll in particular, has its disadvantages. The largest one is that without using some pretty advanced workarounds it is hard to get search engines to recognize content that is lazy loaded in. For some resources, this might not matter. But if you are replacing pagination altogether, content that is buried below the fold might not be read by Google or other search engines. In a true infinite scroll situation, there are also problems that arise when users try to use the back button, or get back to a piece of content from farther up, and are unable to do so.

After all, lazy loading is essentially a hack. It often utilizes a technique that replaces content farther down the page with a placeholder, only to load it in later. Or, for infinite scroll sites, content is loaded in via AJAX when a user’s scroll position hits the bottom. It makes initial page load faster, a lot faster, but user experience still has to be thought through.

Fortunately, if you use lazy loading sparingly, a lot of these negatives go away. You can gain a lot simply by lazy loading images, videos and scripts, while still leaving all of your content and pagination intact. Sure, images will be swapped out with placeholders, but a good alt tag can help this quite a bit.

The first thing we’ll do is go over how to implement image lazy loading in your theme with a few steps. But for more advanced uses of lazy loading, there are a few plugins out there that can help you get up and running automatically.

Adding Image Lazy Loading to Your Theme

To illustrate how you can use lazy loading in your WordPress site, we’ll add delayed loading of images to our site, so that all images are automatically swapped out with a placeholder image, and then loaded when a user scrolls down to it. To accomplish this, we’ll be using the Lazy Load for jQuery plugin.

You can start by creating a child theme, and placing all of the code that follows at the bottom of your functions.php file. However, since this is a piece of functionality, it might also be worth creating a separate plugin, so that it is activated no matter what theme you are using. In both cases, the code is more or less the same.

The first thing to do is gather together our assets. Download the minified version of the jQuery lazy load plugin and add it to a folder labeled “js” in your child theme’s folder. Next, create a folder called “img” and add the below gif file to it. This will be used as our placeholder images for images that are lazy loaded.

Download this

Now we can actually start adding some code. The first thing to do is ensure that our lazy load script is added to our WordPress theme. We do this by using the wp_enqueue_scripts action, making sure to add “jquery” as a dependency for our script. This will ensure that our script is only loaded after jQuery.

function enqueue_lazyload() {
    wp_enqueue_script('jquery_lazy_load', get_stylesheet_directory_uri() . '/js/jquery.lazyload.min.js', array('jquery'), '1.9.1');
}
add_action('wp_enqueue_scripts', 'enqueue_lazyload');

Next, we have to add a small bit of Javascript to our footer to get the lazy load plugin to recognize images. You can see how this works on the plugin’s homepage, but basically we have to specify a class for the plugin to target. It will use any images with this class to swap out a placeholder image with the actual image when a user scrolls to it. We’ll use the wp_footer action to automatically append this to the footer of each one of our pages.

function footer_lazyload() {
    echo '
<script type="text/javascript">
    (function($){
      $("img.lazy").lazyload();
    })(jQuery);
</script>
';
}
add_action('wp_footer', 'footer_lazyload');

With this code in place, the lazy load plugin will actually start working. But our images are still being loaded in by WordPress. The trick is to filter through all of our posts and swap out an image with a placeholder image. Then, per the plugin’s instructions, we use a “data-original” attribute on the img tag to signify the actual URL of the image. Finally, we add a class of “lazy” to each image so jQuery knows to look for it. The lazy load plugin will wait for these images to come into a users view, and then pull them in using AJAX and load them on the page.

Our first step is to add a simple filter using preg_replace_callback to search for img tags.

function filter_lazyload($content) {
    return preg_replace_callback('/(<\s*img[^>]+)(src\s*=\s*"[^"]+")([^>]+>)/i', 'preg_lazyload', $content);
}
add_filter('the_content', 'filter_lazyload');

When called, this function will search through content and find all of the images. It will then pass these images along to the preg_lazyload function which we will talk through below. Next, we use the “the_content” filter to automatically filter through all of our post’s content when a post is rendered. This is not the most performant way to accomplish this, but it works quite well. Each time a post is rendered, all images will be filtered out and run through “preg_lazyload”. What’s that function look like?

function preg_lazyload($img_match) {
    $img_replace = $img_match[1] . 'src="' . get_stylesheet_directory_uri() . '/img/grey.gif" data-original' . substr($img_match[2], 3) . $img_match[3];
    $img_replace = preg_replace('/class\s*=\s*"/i', 'class="lazy ', $img_replace);
    $img_replace .= '<noscript>' . $img_match[0] . '</noscript>';
    return $img_replace;
}

This is where the magic happens. Preg_lazyload takes in all of the images that our filter has found, and does a few things. First, it replaces our “src” with a link to the placeholder image we saved above. Next, it adds the “data-original” attribute, and places the link to our image in it. After that, it appends the HTML class “lazy” to the image so that our plugin knows to look for it and perform an image swap on scroll. As a final precaution, we add the full source of the image in a noscript tag in case a user has Javascript disabled.

Images in your posts will now be lazy loaded in when they appear in a reader’s viewport. This is certainly experimental, and doesn’t account for all cases, but it is meant as a demonstration and a good starting point. In fact, we can already improve this by encapsulating everything in a PHP class and then calling it. I’ve added the full code like this in a gist for reference.

If you are looking for a good implementation as a plugin, you can also check out the GitHub repo from Andrew Ng. Much of the code above is based on his implementation.

Lazy Loading Using Plugins

If you are looking to include more advanced lazy loading techniques in WordPress, there are a few plugins that can help. Each plugin implements lazy loading in different ways, but the result is always the same. A faster page load.

Rocket Lazy Load

A more thorough implementation of the above code can be found in Rocket Lazy Load. It works automatically as soon as you activate it, and will delay the loading of images everywhere on your site until it has come into a reader’s view. And rather than use the jQuery lazy load plugin, it injects a small bit of Javascript into the header of your site which takes care of everything. It has absolutely no options, though you can add a data attribute to images if you want to bypass the functionality. But it is meant to be simple. Activate the plugin to add image lazy loading to your site, and deactivate it to turn it off. Everything else works automatically.

BJ Lazy Load

BJ Lazy Load Plugin

BJ Lazy Load brings a bit more to the table. Rather than focus on just images, BJ Lazy Load allows you to lazy load images and iframes. It also allows you to selectively chose where lazy loading should be applied, in content, text widgets, featured images, or gravatars. After you install and activate the plugin you can configure what assets should be lazy loaded and where by visiting the settings page. On this page, you can also upload your own custom placeholder image if you don’t want to use the one provided by the plugin, and chose certain class names that should be bypassed.

BJ Lazy Load also has a few extra features that make it worth an extra look. It is not an infinite scroll plugin, but it works alongside other popular infinite scroll implementations. And the newest versions of the plugin include support for responsive images. However, this is still pretty new to the plugin, and may not work with every theme out there. But regardless, BJ Lazy Load keeps things fairly lightweight and works behind the scenes for you to speed up your page loads.

Lazy Load for Videos

Lazy Load for Videos Plugin

One of the more resource intensive embeds on any site is third party video embeds from YouTube or Vimeo. They are loaded into your page with several images, scripts and stylesheets to make them work properly. Lazy Load for Videos is a plugin built to address this specific use case. It filters through your embedded videos, and replaces all of these external files with a static image of your thumbnail and a play button. Only when the play button is pushed are these resources actually loaded in. It is a seamless experience for your users, but can really speed up a page with multiple videos on it. And since the plugin hooks into these embeds to make the switch, you also have the ability to customize the look and feel of third party media.

Infinite Scroll

As discussed above, infinite scroll should really only be used if the it fits the content of your site. But if you do want to enable infinite scroll on your site, there are really two plugins you can turn to.

The first is Jetpack, which has an Infinite Scroll module in it. With a little effort, it can work with most themes, but it’s best to refer to the documentation for how it works. The basic principle is, after you activate the module, you need to add a small bit of code to your functions.php file to get it working properly.

add_theme_support( 'infinite-scroll', array(
    'container' => 'container',
    'footer' => 'page',
) );

The “container” parameter is used to define the class name of your content, and the footer parameter is used to add a sticky footer to the bottom of your pages (since users can’t scroll all the way to see it). There may be a few additional steps you have to take to get it working with your theme, but it works fairly well out of the box.

Infinite Scroll Option in Jetpack

The other plugin is Infinite-Scroll, which was developed a few years ago and has since undergone a complete rewrite to keep it compatible with WordPress. The plugin works a lot like the Jetpack module, though you can use the plugin’s settings to define the class of the container you want to target. Once again, you will need to ensure that all of your posts are arranged without pagination, but you can have it up and running fairly quickly.

Of course, if you’re an Elegant Themes user, you should check out the Origin Theme, which has intelligent infinite scroll built in.

Keeping an Eye on Performance

There has been study after study that has confirmed one simple fact. A quicker page load leads to a more satisfied user. Often times, rich media can slow your site down quite a bit, and send your readers somewhere else. Lazy Loading, when implemented properly, can be a simple solution to this problem. Whether it’s on your own, or through a plugin, lazy loading works the same way. Wait until a user sees an image, or video, or iframe, before loading it. And that’s good for performance.

Bookmark the permalink.

About Paige Duewel

Paige Duewel, Local Small Business Entrepreneur and Owner of Marketing Solutions HHI offers Email Blasts, Social Media Marketing, SEO, Branding, Website Design and more!