Exclude Logos and Featured Images From Lazy Loading
Adds the "no-lazyload" class (and matching skip attributes) to the site logo and the featured image of single posts, so Smush and other lazy-load plugins load them immediately and improve Largest Contentful Paint.
Opens WPIDE on
Code
add_filter( 'get_custom_logo_image_attributes', function ( $attr ) {
$attr['class'] = trim( ( isset( $attr['class'] ) ? $attr['class'] : '' ) . ' no-lazyload skip-lazy' );
$attr['loading'] = 'eager';
$attr['data-no-lazy'] = '1';
return $attr;
} );
add_filter( 'wp_get_attachment_image_attributes', function ( $attr, $attachment ) {
if ( is_admin() || ! is_singular() || (int) get_post_thumbnail_id( get_queried_object_id() ) !== (int) $attachment->ID ) {
return $attr;
}
$attr['class'] = trim( ( isset( $attr['class'] ) ? $attr['class'] : '' ) . ' no-lazyload skip-lazy' );
$attr['loading'] = 'eager';
$attr['data-no-lazy'] = '1';
return $attr;
}, 10, 2 );
Notes
Smush, WP Rocket and LiteSpeed all honour these markers; it also turns off native lazy loading for those images.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.