Archived topic
Featured image is lazy loaded and Page Speed complains about it
10 replies · Started by Thorsten on November 20, 2022
Hej,
I have created an element as block hook for generate_before_content and add there a dynamic image. This image is the featured image of the post this block hook will added to.
So Googles page speed complains this image is part of the largest contentful paint area and is lazy loaded. I have searched this forum and tried to add the skip-lazy class to it. Without any change.
And deactivating lazy loading globally in WordPsress and added again with Autoptimized sound a little bit crazy to me, because I don't need Autooptimize at all.
Do you have a solution for this?
Thanks in advance
Thorsten
Hi Thorsten,
Can you try adding an additional CSS class to the image block, eg. featured-image, then add the below snippet:
add_filter( 'render_block', function( $block_content, $block ) {
if ( ! empty( $block['attrs']['className'] ) && 'featured-image' === $block['attrs']['className'] ){
$block_content = str_replace( 'lazy', 'eager', $block_content );
}
return $block_content;
}, 10, 2 );
No, I am sorry, that doesn't work. There is always lodaing="lazy".
Hi Thorsten,
For reference, can you provide the link to the site in question?
You may use the Private Information field for this: https://docs.generatepress.com/article/using-the-premium-support-forum/#private-information
Yes, of course. And the page isn't a great secret, only work in progress.
But you can see it here: Sample page with lazy loaded featured image
The image in the green area is the featured image (in block hook added as dynamic image)
I see. Since you have GenerateBlocks, can you try using a GenerateBlocks Image Block instead for that image, and then add skip-lazy to the class list of this Image Block?
Adding Custom Classes: https://wordpress.com/support/wordpress-editor/adding-additional-css-classes-to-blocks/
I have changed the block hook, but it is always the same :(
Hi there,
WP provides the wp_get_attachment_image_attributes filter hook to set attributes on an image.
And as you have added the skip-lazy class we can use that in that filter to remove the loading attribute.
Try this PHP Snippet:
add_filter( 'wp_get_attachment_image_attributes', 'fp_no_lazy_featured_image', 10, 3 );
function fp_no_lazy_featured_image( $attr ) {
if ( false !== strpos( $attr['class'], 'skip-lazy' ) ) {
unset( $attr['loading'] );
}
return $attr;
}
No change :(
But I have fixed your code snippet:
Instead
unset( $attr['loading'] );
I am using
$attr['loading'] = "eager";
And this finally works.
Glad to hear you got it working.