To preload your LCP you can either use code on functions.php or with Perfmatters.
How to Preload Largest Contentful Paint (LCP) with Permatters
Perfmatters allow you to preload images only when it’s not necessary with a friendly interface.
Use Perfmatters and its conditional preloading to preload assets only on certain parts of your website, or its “Preload Critical Images” beta feature that will automatically preload the number of leading images that you choose (0-5).
How to Preload Largest Contentful Paint (LCP) with code
To preload all the Largest Contentful Paint (LCP) images on all pages, follow the steps:
- Go to Appearance > Theme File Editor > and in the Theme files click to edit functions.php and add the following code:
add_action( 'wp_head', function(){
$featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full');
echo '<link rel="preload" as="image" href="'.$featured_img_url.'"/>';
});
This function uses get_the_post_thumbnail_url() as an LCP image and creates a link preload for it. Some themes may be not compatible, and if your homepage or the page doesn’t have an image thumbnail it will create an empty <link rel=’preload’> tag.
This function doesn’t preload responsive images. Use a WordPress function to preload the image only on the specific pages it appears.
How to Preload a responsive Largest Contentful Paint (LCP) Image with code
To preload a responsive image you can add imgsrcset
and imagesizes
to the <link> element. To preload the following image:
<img src="bear.jpg" srcset="bear_400px.jpg 400w, bear_800px.jpg 800w, bear_1600px.jpg 1600w" sizes="50vw" alt="bear test image">
You can do the following:
<link rel="preload" as="image" href="bear.jpg" imagesrcset="bear_400px.jpg 400w, bear_800px.jpg 800w, bear_1600px.jpg 1600w" imagesizes="50vw">
Final code to be inserted in functions.php and preload a responsive LCP image only on the homepage:
// Preload a responsive image only on homepage
function preload_featured_image_home() {
if (is_front_page()) {
echo '<link rel="preload" as="image" href="/wp-content/uploads/2021/06/cropped-wpalpha-logo-%E2%80%[email protected]" imagesrcset="bear_400px.jpg 400w, bear_800px.jpg 800w, bear_1600px.jpg 1600w" imagesizes="50vw">';
}
}
add_action( 'wp_head', 'preload_featured_image_home', 90 );
Get your WordPress Core Web Vitals Optimized!