Skip to content

Instantly share code, notes, and snippets.

@felixarntz
Last active March 11, 2024 22:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felixarntz/fcf11eeadaaae695dc35fe2c8eacb446 to your computer and use it in GitHub Desktop.
Save felixarntz/fcf11eeadaaae695dc35fe2c8eacb446 to your computer and use it in GitHub Desktop.
Prototype plugin used for lazy-load LCP analysis in WordPress
<?php
/**
* Plugin initialization file
*
* @wordpress-plugin
* Plugin Name: Lazyload LCP Fix
* Plugin URI: https://gist.github.com/felixarntz
* Description: Omits the first content image from being lazy-loaded, to improve LCP performance.
* Version: 1.0.0
* Author: Felix Arntz, Google
* Author URI: https://opensource.google.com
* License: GPL v2 (or later)
*/
function ___img_lazyload_fix( $skip_images = 1 ) {
$first_post_img_count = 0;
// Skip lazy-loading for the featured image of the first post in the current
// main query loop, if is also displayed before any other images in the post.
//
// In WP core this should probably be achieved using a new separate context
// instead, e.g. "featured_image".
add_filter(
'post_thumbnail_html',
function( $image, $post_id ) use ( &$first_post_img_count, $skip_images ) {
if ( ___img_lazyload_is_within_first_loop_posts( $post_id, $skip_images ) ) {
if ( $first_post_img_count < $skip_images ) {
$image = str_replace( ' loading="lazy"', '', $image );
}
$first_post_img_count++;
}
return $image;
},
10,
2
);
// Skip lazy-loading attribute on the first image in the first post in the
// current main query loop.
add_filter(
'wp_img_tag_add_loading_attr',
function( $loading, $image, $context ) use ( &$first_post_img_count, $skip_images ) {
if ( 'the_content' === $context && ___img_lazyload_is_within_first_loop_posts( 0, $skip_images ) ) {
if ( $first_post_img_count < $skip_images ) {
$loading = false;
}
$first_post_img_count++;
}
return $loading;
},
10,
3
);
}
function ___img_lazyload_is_within_first_loop_posts( $post_id = 0, $first_x_posts = 1 ) {
global $wp_query;
if ( ! is_main_query() || ! in_the_loop() ) {
return false;
}
if ( ! $post_id ) {
$post_id = get_the_ID();
}
for ( $i = 0; $i < $first_x_posts; $i++ ) {
if ( isset( $wp_query->posts[ $i ] ) ) {
$check_post = $wp_query->posts[ $i ];
if ( $check_post instanceof WP_Post && (int) $check_post->ID === (int) $post_id ) {
return true;
}
if ( is_scalar( $check_post ) && (int) $check_post === (int) $post_id ) {
return true;
}
}
}
return false;
}
___img_lazyload_fix( 1 );
@felixarntz
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment