How to Preload Largest Contentful Paint (LCP) image in WordPress

Updated on November 4, 2022 | By

To preload all the Largest Contentful Paint (LCP) image on all pages, follow the steps:

  • Go to the 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 LCP image and create a link preload for it. Some themes may be not compatible with this approach, 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.

How to Preload a responsive Largest Contentful Paint (LCP) Image

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 );

Lazyloading the LCP image may delay its appearance. You can disable the lazyload and preload the logo and the first image of the slider, for example. You should avoid lazy loading elements inside the viewport(above the fold), and lazyload images below the fold, outside the viewport.

Preload Largest Contentful Paint (LCP) only when necessary

Avoid preloading images when it’s not necessary, use a WordPress function to preload the image only on the specific pages it appears.

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).

preaload perfmatters
Preload assets with a conditional option
preload critical images perfmatters
“Preload Critical Images” beta feature

Get your Core Web Vitals optimized

Leave a Comment