Forked from warwickandersonza/elementor-preload-background-images.php
Created
June 12, 2024 19:18
-
-
Save dexit/2fe204769cd53d885836e049515a2b9f to your computer and use it in GitHub Desktop.
Preload Elementor background images
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
<?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