Show a big image above the fold could cause a lower score in Large Contentful Paint (LCP) on PageSpeed Insights especially the Mobile test tab. In many cases, we cannot avoid this due to design requirement by customer.
There are many plugins if your website is built by using WordPress. However, I preferred to use code to solve this problem.
Let me share my way on this current Itchycode website too.
Link Types: Preload
We can make use of rel in link type to preload any source whenever visitor browse the url.
If you are interested on it, just explore it here.
<link rel="preload" as="image" href="/image_url.jpg">
Before get your hand dirty, do a PageSpeed Insights test first.
Now, let’s insert this by using wp_head
hook.
<?php
add_action('wp_head', 'itchy_header_script');
function itchy_header_script()
{
?>
<link rel="preload" as="image" href="https://itchycode.com/wp-content/uploads/2021/11/ping-check-on-mcmc-block-03.jpg">
<?php
}
?>
Then inspect and you should see it in your header now.
Well, let’s do another test and… tata~~ you should see a significant improve on the Largest Contentful Paint (LCP).
Dynamically Preload Image Link
Hard-code the image source is not ideal and this will be inserted on every page. Let’s modify it.
WordPress functions used:
get_the_post_thumbnail_url
wp_get_attachment_image_srcset
wp_get_attachment_image_sizes
get_posts
has_post_thumbnail
wp_get_attachment_url
get_post_thumbnail_id
is_singular
Sorry that I am not going to dig into each function in this tutorial.
<?php
function itchy_header_script() {
/*
* If wish to insert the preload link on all single post page because there is a featured image above fold
*/
if((int)get_post_thumbnail_id() > 0 && is_singular('post')) :
?>
<link rel="preload"
as="image"
href="<?php echo get_the_post_thumbnail_url();?>"
imagesrcset="<?php echo wp_get_attachment_image_srcset(get_post_thumbnail_id());?>">
<?php
endif;
/*
* Itchycode front page is showing all posts and orderby descending. I just wish to preload the first 2 featured images.
*/
if(is_front_page()):
$args = array(
"post_type" => 'post',
"numberposts" => 2,
"orderby" => "date",
"order" => "desc"
);
$my_posts = get_posts( $args );
if ($my_posts) {
foreach($my_posts as $i=>$my_post) {
if ( has_post_thumbnail( $my_post->ID ) ) {
$imgURL = wp_get_attachment_url( get_post_thumbnail_id( $my_post->ID ), 'full' );
?>
<link rel="preload"
as="image"
href="<?php echo $imgURL;?>"
imagesrcset="<?php echo wp_get_attachment_image_srcset( get_post_thumbnail_id( $my_post->ID ) );?>"
imagesizes="<?php echo wp_get_attachment_image_sizes( get_post_thumbnail_id( $my_post->ID ) );?>" >
<?php
}
}
}
endif;
}
?>
From the code above, I am able to insert the preload link on first page and also single post only.
You are free to use it as a reference and modify to suit your own website.
This is really helpful!