Optimizing your site for your visitors as well as Google and other search engones are important tasks, if you are serious about your interent presentation.
Google offers the Google Search Console to point out specific metrics that Google believes, should be improved. One of those metrics that come up a lot is called LCP. The largest contentful paint..
LCP-Metriken messen die Renderzeit des größten Bild- oder Textblocks, der im Darstellungsbereich sichtbar ist. Also im Grunde das größte Element „above the fold“. Das ist ziemlich oft ein Bild, besonders bei Blogposts oder anderen inhaltsreichen Seiten.
The issue here is, that wordpress started to lazy load all images of the site in Wordpress 5.4. It is a standard function, which is a great improvement. However in this case it would be better that the first image of the content would not be loaded using lazy load. Espescially if your site displays it abover the content and therefor above the fold.
The reason for this is that images being lazy loaded, are loading quite a bit slower. Therefor the LCP score often is a lot worse than it could. Google's Pagespeed Insights actually suggests not to load the LCP using lazy loading quite often.
Since I had this issue before for several clients I cam up with a simple code hat can be pasted into the functions.php of your Wordpress theme.
//function to get first image in post content area
function get_first_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img[^>]*src="([^"]+)"/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
//defines a default image if no image was found
if(empty($first_img)){
$first_img = "/images/default.jpg";
}
return $first_img;
}
// disable lazy loading for first image inside post content
function no_lazy_load_on_first_image( $value, $image, $context ) {
if ( 'the_content' === $context ) {
//uses above function to check if image is the first image of the content area
$image_url = get_first_image();
if ( false !== strpos( $image, '' . $image_url . '' )) {
return false;
}
}
return $value;
}
add_filter( 'wp_img_tag_add_loading_attr', 'no_lazy_load_on_first_image', 10, 3);
Dieser Code verwendet tatsächlich zwei Funktionen und den WP-Filter „wp_img_tag_add_loading_attr“. Mit diesem Filter können wir ändern, wie Lazy Loading hinzugefügt wird.
The first function finds the first image within the current post content. The second function simply checks if this is the image the filter is currently passing through. If so, false is returned instead of the regular value.
Feel free to improve, correct and comment on the code snippet below.