How to Use Lozad.js in Sage

Lozad.js is a lightweight lazy-loading library that’s just 535 bytes minified & gzipped.

It is written with an aim to lazy load images, iframes, ads, videos or any other element using the recently added Intersection Observer API with tremendous performance benefits.


yarn add lozad

Import and add JS

Open resources/assets/scripts/routes/common.js and add the import to the top of the file:

import lozad from 'lozad';

And then within the init function, add:

const observer = lozad();

…or with some options defined:

const observer = lozad('.lozad', {
  rootMargin: '500px 0px',
  threshold: 0.1,
  load: function(el) {
    el.src = el.dataset.src;

Tell WordPress to lazy load images

Add to app/filters.php:

 * Use Lozad (lazy loading) for attachments/featured images
add_filter('wp_get_attachment_image_attributes', function ($attr, $attachment) {
    // Bail on admin
    if (is_admin()) {
        return $attr;

    $attr['data-src'] = $attr['src'];
    $attr['class'] .= ' lozad';

    return $attr;
}, 10, 2);

Template file usage

Rather than using <img src> in your templates, use <img data-src="path-to-src.jpg" class="lozad">.


Browser support for the Intersection Observer API isn’t the greatest, but there are a few different options for implementing a fallback:

Join the discussion on Roots Discourse

Help support our open-source development efforts

Help us grow

Join over 7,800+ subscribers on our newsletter to get the latest Roots updates, along with occasional tips on building better WordPress sites.

Looking for WordPress plugin recommendations, the newest modern WordPress projects, and general web development tips and articles?

“Easily the best WordPress email I get.” Colin OBrien

Follow us on Twitter @rootswp

Ready to checkout?