Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dexit/2fe204769cd53d885836e049515a2b9f to your computer and use it in GitHub Desktop.
Save dexit/2fe204769cd53d885836e049515a2b9f to your computer and use it in GitHub Desktop.
Preload Elementor background images
<?php
/**
* Preload Elementor background images if they are among the first elements on a page.
*
* @return void
*/
function sitecare_preload_elementor_background_images(): void {
if ( ! did_action( 'elementor/loaded' ) ) {
return;
}
$elementor_data_string = get_post_meta( get_the_ID(), '_elementor_data', true );
if ( ! $elementor_data_string ) {
return;
}
$elementor_data = json_decode( $elementor_data_string );
if ( is_null( $elementor_data ) ) {
return;
}
$preloaded_images = array();
for ( $i = 0; $i < (int) apply_filters( 'sitecare_elementor_bg_section_depth', 1 ); $i++ ) {
$elementor_section = $elementor_data[ $i ] ?? null;
if ( is_null( $elementor_section ) ) {
continue;
}
if ( ! empty( $elementor_section->settings?->background_image?->url ) ) {
$preloaded_images[] = $elementor_section->settings->background_image->url;
}
for ( $j = 0; $j < (int) apply_filters( 'sitecare_elementor_bg_column_depth', 1 ); $j++ ) {
$elementor_column = $elementor_section->elements[ $j ] ?? null;
if ( is_null( $elementor_column ) ) {
continue;
}
if ( ! empty( $elementor_column->settings?->background_image?->url ) ) {
$preloaded_images[] = $elementor_column->settings->background_image->url;
}
}
}
foreach ( $preloaded_images as $preloaded_image ) {
printf( '<link rel="preload" href="%s" as="image" fetchpriority="high">', $preloaded_image );
}
}
add_action( 'wp_head', 'sitecare_preload_elementor_background_images', -10 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment