Site logo

Archived topic

Exclude featured image from WP fastest cache lazy load

12 replies · Started by Bernhard on October 16, 2020

Viewing posts 1–13 of 13

Hello,
is it possible to exclude the featured images from lazy loading?
WP Fastest Cache has an attribute
data-skip-lazy="1"
and give a sample
<img src="sample.jpg" data-skip-lazy="1" alt="" width="100" width="100" />
but I don't know how to address the featured images.

Hi there,

Are you referring to the featured images on the blog page or single posts?

Let me know :)

Hi Leo,
single posts and pages.

Can you give this a shot?

add_filter( 'wp_get_attachment_image_attributes', function( $attrs ) {
    if ( is_single() || is_page() ) {
        $attrs['data-skip-lazy'] = '1';
    }

    return $attrs;
} );

Adding PHP: https://docs.generatepress.com/article/adding-php/

Hi Leo,
I inserted the code and it seems to work. Page Speed Inside gives me now CLS=0.
Can you please verify from your side if it is ok.
Thank you.

Don't think you've provided the site link but I assume it's all good :)

Not sure if I fully understand,

This page doesn't have a featured image.

So we are all good now?

I don't believe you can add a data attribute to background images.

@Leo – thanks for this snippet!

The only place on my site that Featured Images (post thumbnails) are displayed is on archive and index (home) pages... So, I tweaked the snippet a bit to force loading only on the first Featured Image on the page, but then leave the rest to be lazy loaded:

add_filter( 'wp_get_attachment_image_attributes', function( $attrs ) {
	global $wp_query;

	if ( $wp_query->current_post === 0 )
		$attrs['data-skip-lazy'] = '1';

	return $attrs;
} );

If you want to disable lazy loading on more than just the first one, then you could just change the conditional in the snippet (e.g., < 3 to load the first three on the page, instead of === 0 to load only the first).

Thanks for sharing!

This archived topic is closed to new replies.