Last active
September 30, 2021 02:19
-
-
Save blogjunkie/e86b92d4c2782018ecd43301b2934d56 to your computer and use it in GitHub Desktop.
Preload site logo and LCP image in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php // don't copy this line | |
/** | |
* Modify the $image_id variable and replace 'medium_large' with desired image size | |
* See: https://web.dev/optimize-lcp/?utm_source=lighthouse&utm_medium=unknown#preload-important-resources | |
* Note: don't go overboard and preload too many assets, just ones that appear above the fold | |
*/ | |
add_action( 'wp_head', 'child_preload_assets', 1 ); | |
function child_preload_assets() { | |
// Preload the logo on every page | |
echo "<!-- preload logo -->\n"; | |
echo '<link rel="preload" as="image" href="'. esc_url( wp_get_attachment_url( get_theme_mod( 'custom_logo' ) ) ) .'">'; | |
// Preload LCP image on important pages | |
if ( is_front_page() ) { | |
echo "<!-- preload LCP image -->\n"; | |
$image_id = 5812; | |
$image = wp_get_attachment_image_src( $image_id, 'medium_large' ); // returns array of image data | |
$srcset = wp_get_attachment_image_srcset( $image_id, 'medium_large' ); | |
$sizes = wp_get_attachment_image_sizes( $image_id, 'medium_large' ); | |
if ( $image ) { | |
echo '<link rel="preload" as="image" href="'. $image[0] .'" imagesrcset="'. $srcset .'" imagesizes="'. $sizes .'">'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment