Enable Lazy Loading in WordPress using Perfmatters: A Step-by-Step Guide

How To Enable Lazy Loading in WordPress using Perfmatters

Looking to enable lazy loading in WordPress while using Perfmatters Plugin?

You’ve come to the right spot!

As web content becomes lengthier, it’s crucial to make use of features such as lazy loading in WordPress to maintain the speed of your site.

What is lazy loading?

Lazy loading means holding off or postponing the loading of images until a user scrolls down the page, and the images come into view.

Why is this great? Let’s say you’ve got a long blog post with around 100 images. Normally, the browser tries to load all 100 images as soon as someone opens the post. Even if the images are optimized, this can take a while, especially on mobile.

But with lazy loading, it only loads the images at the top of the page that visitors can see in their browser.

The exact number of images loaded depends on the type of browser, the specific lazy loading method used, the size of the viewport, and so on.

However, the main idea is that it usually reduces the number of image requests by more than 85% right from the start.

In addition to reducing requests, lazy loading also takes care of the “Defer offscreen images” warning you might get from PageSpeed Insights.

Defer offscreen images PageSpeed Insights warning

Lazy load test

We did a simple test on one of our blog posts to show you the change.

Before Enable Lazy Loading

Here is how things looked before we enabled lazy loading on the images. You can see there were a total of 56 requests, the whole page size was 852 KB, and it took 1.2 seconds to load.

before enable lazy loading

After Enable Lazy Loading

Here’s how things looked after we enabled on lazy loading. You can observe that the number of requests went down to 35, the total page size reduced to 245 KB, and the load time decreased to 0.8 seconds. To put it simply, just by turning on lazy loading, we experienced a 33% speed boost and a 70% reduction in page size.

After Enable Lazy Loading

The post we tested was already quite optimized. You’d notice even more significant speed improvements if you’re lazy loading images that aren’t optimized or if there are more images on a page.

How Perfmatters lazy loading works

Perfmatters uses a small (2.5 KB), open-source JavaScript library to lazy load images, iframes, and more. They also support lazy-loading WebP files. You’ll notice a request to the following file on your site:

/perfmatters/js/lazyload.min.js

Perfmatters lazy loading vs native lazy loading

WordPress 5.5 comes with native lazy loading by default. However, we recommend using the lazy loading solution in Perfmatters.

Here’s why: Perfmatters solution is faster and better than native lazy loading for these reasons:

  1. Controlled Eager Loading:
    • Native lazy loading lets the browser decide what to lazy load, but it tends to be too eager by default. While it may not require many exclusions, it may not lazy load as many resources, resulting in slower loading times.
  2. Media Library Requirements:
    • Native lazy loading requires images to be uploaded to the WordPress media library with added width and height. This means it might not apply to all elements.
  3. CSS Background Images:
    • Native lazy loading doesn’t support background images in CSS, which our solution covers.
  4. Feature Support and Improvements:
    • Our lazy loading solution in Perfmatters has more features and continuous improvements compared to native lazy loading.

Important Note: When lazy loading is enabled in Perfmatters, the default native lazy loading in WordPress is automatically disabled.

Here’s how you can enable lazy loading in WordPress:

To activate lazy loading in WordPress, make sure you’ve disabled it in other places like additional optimization plugins or your theme.

Navigate to the “Perfmatters” settings in your WordPress admin dashboard.

Perfmatters settings in WordPress admin dashboard

Click on the “Lazy Loading” submenu.

Lazy Loading Submenu option in perfmatters

There are a few choices for lazy loading, and you can use them simultaneously.

Lazy load images

The primary and widely used option is to apply lazy loading to your images. Simply switch on the “Images” option to enable this. It covers inline background images within the style attribute as well.

lazy load images option

Exclude leading images

You can choose not to lazy load specific images manually, but sometimes it’s simpler to automate this. The “Exclude Leading Images” feature helps with that. It allows you to automatically skip a certain number of images from the top of the page (the ones visible without scrolling).

option for Exclude leading images

Note: Make sure you’re not logged in when figuring out or testing the number of images to exclude. The automated exclusions won’t apply to background images.

If you’re utilizing the preload critical images feature, it will automatically exempt those images from lazy loading. Therefore, you might not need to use the exclude leading images option.

Lazy load iframes and videos

The next choice is to apply lazy loading to iframes and videos. This covers content from platforms like YouTube, Vimeo, SoundCloud, Google Maps, and any other type of iframe. It also applies to videos embedded using the video tag with a file URL.

To activate this, switch on the “iFrames and Videos” option.

lazy loading iFrames and videos option

YouTube preview thumbnails

If you have YouTube videos on your website, it can be beneficial to activate the preview thumbnail feature. This feature replaces YouTube iframes with a preview thumbnail and a lightweight SVG play icon. The iframe loads when clicked, providing the fastest way to load YouTube videos.

In performance tests with videos, we observed a 64% increase in site speed and a 58% reduction in total page size with this feature enabled. That’s quite remarkable.

Before: 1.93s load time with a total page size of 691 KB. After (with lazy load enabled): 0.72s load time with a total page size of 288 KB.

The preview image used on YouTube is automatically pulled as the thumbnail. The example below illustrates this.

YouTube preview thumbnails Example

To activate this, switch on the “YouTube Preview Thumbnails” option. Please note that this requires enabling iFrames and Videos in Perfmatters.

YouTube preview thumbnail quality filter

For the YouTube preview thumbnail quality, the default setting pulls a low-resolution image from YouTube. However, there’s a filter you can use to adjust the quality of the thumbnail. The “maxresdefault” attribute will fetch the highest available quality. Ensure your YouTube thumbnails are at least 1280 x 720 pixels. Refer to this helpful guide on sizing your YouTube thumbnails. Explore additional options for the filter.

add_filter('perfmatters_lazyload_youtube_thumbnail_resolution', function($resolution) {
return 'maxresdefault';
});

You can also utilize the wp_is_mobile function to display low-resolution images on mobile devices and high-resolution thumbnails on desktops.

add_filter('perfmatters_lazyload_youtube_thumbnail_resolution', function($resolution) {
if(!wp_is_mobile()) {
$resolution = 'maxresdefault';
}
return $resolution;
});

DOM Monitoring

To activate this feature, turn on the “DOM Monitoring” option. This function keeps an eye on changes in the webpage structure (DOM) and efficiently lazy loads newly added elements.

It enhances compatibility with third-party plugins and themes that make use of features like infinite scrolling or gallery sliders.

DOM Monitoring in Lazy Loading in wordpress using perfmatters

If you’re not utilizing infinite scrolling, it’s advisable not to activate this option.

To prevent specific images from being lazy-loaded, you have a couple of methods:

  1. Using Perfmatters UI:
    • The simplest approach is through the Perfmatters user interface (UI).
    • Exclude an element by specifying the source URL (e.g., example.png) or any unique part of its attribute string (e.g., class=”example”).
    • Format: one per line

Exclude images from lazy loading

If you’re not utilizing infinite scrolling, it’s advisable not to activate this option.

To prevent specific images from being lazy-loaded, you have a couple of methods:

  1. Using Perfmatters UI:
    • The simplest approach is through the Perfmatters user interface (UI).
    • Exclude an element by specifying the source URL (e.g., example.png) or any unique part of its attribute string (e.g., class=”example”).
    • Format: one per line
Exclude from Lazy Loading in wordpress using perfmatters

Suppose you’re using a plugin such as ShortPixel or Imagify that delivers WebP images, and you need to target the <picture> tag. In such cases, consider the following examples:

  1. Excluding logo from lazy loading (GeneratePress theme):
    • If you use a theme like GeneratePress and wish to exclude the logo from lazy loading, add their class, such as is-logo-image.
  2. Excluding featured images from lazy loading (blog posts):
    • If you want to exclude featured images from lazy loading in your blog posts, use their class, for instance, class="attachment-full size-full".

Exclude by Parent Selector

Numerous featured images and galleries located above the fold might lack a distinct class on their image tags, making global exclusion challenging. However, these images typically share a pattern or unique string within their parent container.

To exclude particular images from lazy loading, add any unique portion of an attribute string (e.g., class="example") from the parent container. Please note that this feature requires enabling Advanced Options.

exclude by parent selecter option in lazyloading in wordpress while using perfmatters

no-lazy CSS class

To prevent a specific image from being subjected to lazy loading, you can use the “no-lazy” CSS class. By adding this class to the particular image, it will be bypassed during the document’s preparation for lazy loading.

perfmatters_lazyload_excluded_attributes filter

Additionally, Perfmatters offers a WordPress filter, “perfmatters_lazyload_excluded_attributes,” which allows you to exclude images based on specific attributes. In the provided examples:

Targeting images with either the title=’Perfmatters’ attribute or the partial class=’size-full attribute:

phpCopy code

function perfmatters_lazyload_exclude_attributes($attributes) {
$attributes[] = "title='Perfmatters'";
$attributes[] = "class='size-full";

 return $attributes;

}
add_filter('perfmatters_lazyload_excluded_attributes', 'perfmatters_lazyload_exclude_attributes');

Excluding images based on the file name match:

phpCopy code

function perfmatters_lazyload_exclude_attributes($attributes) {
$attributes[] = 'src="https://domain.com/image.png"';

 return $attributes;

}
add_filter('perfmatters_lazyload_excluded_attributes', 'perfmatters_lazyload_exclude_attributes');

Feel free to reach out if you have any questions about using this filter in different scenarios.

Exclude page/post from lazy loading

Additionally, if you wish to exclude an entire post, page, or custom post type from lazy loading, you can do so in the editor by unchecking the “Lazy Loading” option on the right-hand side. This will exclude the entire page from the lazy loading script.

Exclude page post from lazy loading in wordpress using perfmatters

How to change the viewport threshold

If necessary, you can adjust the lazy loading threshold to determine when images start loading before they become visible in the viewport. The default setting is 0 pixels, which is the most aggressive and optimal for performance.

However, some users might choose to increase this value for a smoother scrolling experience. In simpler terms, a higher threshold reduces the occurrence of images suddenly appearing as you scroll down the page.

You can input values in pixels or percentages in the threshold field.

Threshold option in lazy loading in wordpress using perfmatters

You have the flexibility to adjust the lazy loading viewport threshold by utilizing the following filter. Feel free to input values either in pixels or percentages.

add_filter('perfmatters_lazyload_threshold', function($threshold) { return '500px'; });

Note: If your website has numerous third-party JavaScript scripts, such as those from ad networks like Mediavine or AdThrive, we suggest adjusting the viewport threshold to a minimum of 300 pixels.

Fade in

If you prefer a gradual appearance of images as you scroll down a page, giving a smoother transition instead of an abrupt appearance after lazy loading, you can activate the “Fade In” option by toggling it on.

Fade In option

If you wish to adjust the speed of the fade-in transition, you can use #perfmatters_fade_in_speed filter.

CSS background images

Perfmatters seamlessly supports lazy loading inline background images without requiring extra configuration. However, certain page builders, themes, and plugins load background images in their (CSS) stylesheets.

While Perfmatters cannot modify their CSS content, it can prevent specific containers from immediately loading their background images in the browser.

This capability allows you to apply lazy loading to CSS background images in tools like GenerateBlocks, Elementor, Oxygen, Divi, Beaver Builder, etc. To enable this feature, switch on the “CSS Background Images” option.

In the box labeled “Background Selectors,” enter a specific ID or class that corresponds to the container containing the background image. Format: one per line.

Background Selectors options

If your page builder or theme lacks unique classes on the divs that hold background images, and you wish to avoid lazy loading hero images or those above the fold, you can add perfmatters-lazy-css-bg class. For instance, in Elementor, include it in the CSS Classes field of the div containing the background image.

Lazy load background image in Elementor

Forcing an element to lazy load

In some cases, an element from another plugin or theme might already have an exclusion class or attribute, preventing lazy load from working by default. If this occurs, you can potentially force that element to lazy load using the following filter.

phpCopy code

function perfmatters_lazyload_force_attributes($attributes) {
$attributes[] = "title='Perfmatters'";
$attributes[] = "class='size-full";

 return $attributes;

}
add_filter('perfmatters_lazyload_forced_attributes', 'perfmatters_lazyload_force_attributes');

This filter works similarly to the excluded attributes example, but when an element contains one of the included attributes, the lazy loader will skip checking that item for exclusions and continue attempting to lazy load that element.

Troubleshooting

If you’re encountering issues with images not loading, consider these troubleshooting tips:

Image Source Appears as SVG Code:

If your images aren’t loading with lazy load enabled, and the image source looks like the example below, it indicates that you’re likely deferring the lazy loading script.

data:image/svg+xml,%3Csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0’%0%0/svg

To resolve this, exclude the /perfmatters/js/lazyload.min.js script from deferring.

Unable to Lazy Load CSS Background Image:

If a theme or page builder uses a !important class on the background image, it takes precedence, and there might be limitations. Using !important on everything is discouraged and should only be used as a last resort.

Extra Space with YouTube Preview Thumbnails:

If you notice extra space above or below YouTube preview thumbnails, it’s likely that the theme or page builder is using a similar method for their video container. You can address this with some CSS adjustments. Here are a few examples:

For Bricks:

.brxe-video .perfmatters-lazy-youtube {
margin-top: -56.25%;
}

For Oxygen:

.oxygen-vsb-responsive-video-wrapper .perfmatters-lazy-youtube {
margin-bottom: -56.25%;
}

Working with GDPR Plugins:

If you’re using the YouTube preview thumbnails feature alongside GDPR plugins, they might block certain elements from loading. For instance, with the Complianze plugin, you’ll need to exclude the following iframe from lazy loading in Perfmatters:

cmplz-iframe

Exciting Announcement for Our Readers: Perfmatters Now Available, Starting at $6.99.

Also Read: How to Optimize Website Performance with Perfmatters: A Comprehensive Guide

Conclusion

In conclusion, enabling lazy loading in WordPress can significantly enhance your website’s performance by deferring the loading of images until they are actually needed. This not only speeds up the initial page load but also reduces the overall page size and improves the user experience, especially on mobile devices.

Perfmatters provides an effective solution for lazy loading, offering a range of options and features to customize the process according to your specific needs. By optimizing image loading, excluding unnecessary elements, and providing additional controls, Perfmatters empowers you to achieve faster page speeds and a more efficient website.

If you’re facing any challenges or seeking to troubleshoot common issues, the provided tips and filters in Perfmatters offer solutions to ensure a smooth and effective lazy loading implementation. Remember to tailor the settings based on your site’s characteristics and requirements.

In a digital landscape where website speed is crucial for user satisfaction and search engine rankings, incorporating lazy loading with Perfmatters is a valuable strategy for WordPress site owners.

Unlock access to all WordPress premium products

Instantly access our all-in-one bundle of premium WordPress themes and plugins. Valued at $1490, you save about 99%
All-Access • $14.99



Leave a Reply

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

This site uses cookies to offer you a better browsing experience.