Lazy Load Instagram Feed

Hi,

From my understanding there is no option to lazy load images in an Instagram feed element. Does anyone know any workarounds to enable lazy loading on Instagram feed images within the element?

Thank you!

I am also interested in this. I try to implement the instagram feed to load via ajax after page load. We will see, I will report back if I succeed.

I included a functions.php or plugin snippet so the images are lazy loaded:

// Instagram feed images lazy load
add_action('template_redirect', function () {
    ob_start(function ($html) {
        if (strpos($html, 'brxe-instagram-feed') === false) {
            return $html; // it exits if there is no instagram feed
        }

        return preg_replace_callback(
            '/(<div[^>]+class="[^"]*brxe-instagram-feed[^"]*"[^>]*>)(<ul>.*?<\/ul>)(<\/div>)/s',
            function ($matches) {
                $inner = preg_replace(
                    '/<img(?![^>]*\bloading=)/',
                    '<img loading="lazy"',
                    $matches[2]
                );
                return $matches[1] . $inner . $matches[3];
            },
            $html
        );
    });
});
1 Like

Just tested this and it worked for me. Thanks for sharing the snippet! Definitely a helpful workaround unless this gets added as a built-in option later.

1 Like