Created
January 25, 2022 14:24
-
-
Save sabrina-zeidan/0b690749f941ff34346c463c9e0b68c4 to your computer and use it in GitHub Desktop.
Preload 1st image set in ACF Flexible content
This file contains 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
// Preload the first image of the homepage dynamically | |
// In case homepage section that is displayed above the fold is modified this will preload the needed image | |
add_action( 'wp_head', 'sz_preload_first_image'); | |
function sz_preload_first_image() { | |
if( is_front_page() ) { | |
if ( have_rows( 'home_sections' ) ) { | |
while ( have_rows( 'home_sections' ) ) : the_row(); | |
if (get_row_layout() == 'book') { | |
$content = get_sub_field( 'field_5c70983b528e8' ); | |
$document = new DOMDocument(); | |
libxml_use_internal_errors(true); | |
$document->loadHTML($content); | |
$imgs = $document->getElementsByTagName('img'); | |
if (count($imgs) > 0){ | |
$image_src = $imgs[0]->getAttribute('src'); | |
$image_srcset = $imgs[0]->getAttribute('srcset'); | |
echo(PHP_EOL .'<link rel="preload" src="'.$image_src.'" as="image" srcset="'.$image_srcset.'">'.PHP_EOL); | |
break; //get the 1st image only | |
} | |
} | |
endwhile; | |
reset_rows(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment