How to Defer Offscreen Images in WordPress With Lazy Loading

How to Defer Offscreen Images in WordPress With Lazy Loading

One of Google PageSpeed Insights performance suggestions is to defer offscreen images in WordPress with lazy loading.

Lazy loading images in WordPress lowers the initial load time and page payload, without sacrificing content. Lazy loading improves your visitor’s experience, by serving only what your visitors need when they need it. It’s way more efficient than the load-all-the-images-just-in-case approach that results in a slow loading image traffic jam.

In this post, I’m going to show you how lazy loading can improve page performance and how it works. Then we’ll look at how to lazy load your images in WordPress. Continue reading, or jump ahead using these links:

What is Lazy Loading?

Lazy loading is a technique for improving initial page speed and payload by deferring the loading of non-critical assets that are “below-the-fold” or in other words, everything that is not currently in the browser viewport. To defer offscreen images in WordPress basically means to wait to load the images we can’t see yet.

Notice I said assets and not images because a lot of things on your webpage can be lazy loaded, so long as they’re not needed to serve up the site layout and the top of the webpage that your visitor first sees.

Images are an ideal use case for lazy loading because they’re so resource intensive. Videos, scripts, and comments are also ideal candidates because they tend to add a lot of weight to a webpage.

With lazy loading, an asset doesn’t load until the moment is needed, but if the user never reaches it, then it is never loaded at all.

Why is Lazy Loading Better Than Regular Loading?

Lazy loading your images in WordPress improves site performance, SEO and your visitor’s experience.

Lazy loading serves up a much lighter initial webpage and adds elements as needed. With lazy loading, the browser will first build the DOM so your user can begin interacting with your site, even when the full page isn’t finished loading.

Lazy loading doesn’t actually make your image files or your webpage file size smaller. If you have a 3MB page size, that’s how big your page will be with or without lazy loading. This isn’t like compressing images. But lazy loading will greatly improve how your user perceives your site. It feels faster and that may just be enough to keep them on the page.

Google also uses pages peed as a ranking factor and recommends lazy loading images in order to improve performance. We also know that Google rewards faster sites with higher rankings, so lazy loading your images is a way to indirectly improve your image SEO.

Screenshot 89 Google Pagespeed Score Lazy Loading Example
Before activating Smush Pro lazy loading

I created a page with several huge images. I ran an audit of my test site on Google PageSpeed Insights and my score increased from 89 to 91 just by adding lazy loading using Smush Pro (yup, Smush now has lazy loading). That may not seem like a lot, but that is the difference between average (50-89) and fast (90-100) my friends.

Screenshot 91 Google Pagespeed Score Lazy Loading Example
After activating Smush Pro lazy loading

Lazy loading also uses less data. Your visitors who are using a slow mobile connection will thank you. Lazy loading cuts down the resources used when a visitor doesn’t load all your images because they stopped browsing and moved on to the next page.

How Does Lazy Loading Work?

Here’s how you would defer offscreen images in WordPress without a plugin.

First off, you need to determine what images you want to lazy load. You should lazy load any images that are not visible in the viewport and do not contribute to the structure of your page. For example, logo images in the header or hero images above your body text should not be lazy loaded. To provide the best user experience, you should also load images that are within about 500px of the viewport, so they have time to load before the visitor gets to them.

Prevent Images from Loading the Normal Way

When you utilize lazy loading, you need to prevent images from loading the regular way on your site. One way to do this for images utilizing the <img> tag is by removing the image URL from the src attribute and moving it to another attribute, such as data-src, to be stored there temporarily.

Determine How the Browser will Detect Images in the Viewport

The next thing you need to do is address how the browser will determine if the image has entered the viewport. You can use either a Javascript Event Handler or the Intersection Observer API.

JavaScript Event Handler

If browser compatibility is crucial, then using the scroll, resize and orientationchange JavaScript event handlers are the ideal way to determine if an element has reached the viewport because this method is compatible with all browsers. Unfortunately, this requires that you include an additional step to detect element visibility using getBoundingClientRect. It can also cause a slight delay when rendering images.  You can see an example here.

FREE EBOOK
Your step-by-step roadmap to a profitable web dev business. From landing more clients to scaling like crazy.

By downloading this ebook I consent to occasionally receive emails from WPMU DEV.
We keep your email 100% private and do not spam.

FREE EBOOK
Plan, build, and launch your next WP site without a hitch. Our checklist makes the process easy and repeatable.

By downloading this ebook I consent to occasionally receive emails from WPMU DEV.
We keep your email 100% private and do not spam.

The Intersection Observer API

The Intersection Observer API is the modern and most efficient way for compatible browsers to figure out when an image has crossed into the viewport. It’s also faster than using event handlers. You’ll write way less code because you can skip the part where you have to come up with an image visibility detection method and just register an observer to watch the elements and determine what the browser should do when the image is visible.

The Intersection Observer API has pretty good support among browsers, but it hasn’t been universally adopted yet, so you may need to use Javascript event handlers as a fallback for non-compatible browsers.

Move the Image URL to the src Attribute

Once the browser detects that the image is “on stage” or close to it, then it’s time to pull the image URL into the src or srcset attribute so that the image can be downloaded and rendered. When this is done, we can remove any classes added to the image to help your JavaScript code identify it, and remove the observer.

How to Lazy Load Images in WordPress

Lazy loading can be added to your WordPress site with plugins or Javascript. All produce similar results. Lazy loading is relatively easy to implement, so even if you opt for a plugin, the file sizes are generally around 1-3kb and therefore light.

Option 1: Use Plain JavaScript to Defer Offscreen Images in WordPress

If you’re comfortable using straight JavaScript and want full control, you can add lazy loading directly to your site. The best way to add this functionality is to create a plugin for your JavaScript code of course. There are two examples on this page. One shows you how to use event handlers and the other shows you how to use the Intersection Observer API.

Option 2: Use JavaScript Lazy Loading Library

If you want to use a JavaScript library to help, there’s a lot to choose from. Many adhere to the process I’ve described above so you can get started quickly.

  • react-lazyload – A React lazy loading library, doesn’t use Intersection Observer
  • lozad.js – Only uses Intersection Observer, super lightweight
  • blazy – Also super lightweight, but doesn’t use Intersection Observer
  • yall.js – Uses Intersection Observer and falls back to event handlers
  • lazysizes – Can lazy load video and iframes also

You can also use a jQuery plugin for the job since jQuery is included in WordPress core.

Option 3: Use a Lazy Load Plugin

UY7pOM1VnjY

But by far the easiest way to get started with lazy loading is to use a WordPress plugin.

Most premium image optimization plugins, like Smush Pro, have lazy loading built right in. We’ve also included it in our free version of Smush on WordPress.org

To activate lazy loading with Smush, we’ve made the process super duper simple. All you need to do is go to the Lazy Loading section in Smush Pro and push the Activate button.

Screenshot of Smush Pro lazy loading settings
Install Smush Pro and get lazy loading in less than 2 minutes

That’s it. If you want more control over what images are lazy loaded, you’ll have additional options available once you activate lazy loading. When you activate lazy loading in Smush Pro you’ll also lazy load your images for mobile users.

Things to Watch Out for When Lazy Loading Images

  • While lazy loading may not add extra weight that slows down your site, it can interfere with the search engine’s ability to crawl your site if not done correctly.
  • When trying to keep images above the fold, the fold varies by device, so keep this in mind when you’re trying to decide what images to defer.
  • Use a placeholder image instead of leaving the src attribute blank. And specify a height and width for your image so your content doesn’t shift as your images load.
  • Use <noscript> markup to specify what should happen if your visitor has JavaScript disabled.

That’s All

Deferring offscreen images and other assets is a great and easy way to improve your site performance. This technique will work for all the images in an <img> tag on your site, from images on your home page to the images in your posts and pages. If you want to lazy load background images in CSS, you’ll use a similar technique, but you’ll use CSS identifiers to target the images. Here’s an example of how to lazy load background images.

The easiest way to get started with lazy loading is with Smush free or Smush Pro. Smush Pro adds other features that can help you with other Google PageSpeed Insights opportunities. It can help you serve images in next-gen formats by converting your images to WebP files and properly size images by scaling your images with the Smush Pro CDN. Smush Pro is even compatible with the popular WP Retina 2x plugin, so you can lazy load those huge Retina images without slowing down WordPress.

Try Smush Pro free on its own or as part of a membership free trial and see how much of a difference it can make for your site.

Have you tried lazy loading images on your site yet? Did it improve your grade in Google Pagespeed Insights?

Tags:

Felicia Ceballos-Marroquin Felicia is a WordPress expert, specializing in web design/development, search engine optimization, Genesis, and enterprise WordPress multisite. She is a former WPMU DEV author, where she put her decade-plus of WordPress expertise to good use, writing friendly tutorials with soul.