Last active
March 3, 2021 11:57
-
-
Save gyrus/3157238 to your computer and use it in GitHub Desktop.
WordPress image preloading
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
/** | |
* Image preloader | |
* | |
* @link http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript | |
*/ | |
var cache = []; | |
// Arguments are image paths relative to the current page. | |
function pilau_preload_images() { | |
var args_len, i, cache_image; | |
args_len = arguments.length; | |
for ( i = args_len; i--;) { | |
cache_image = document.createElement('img'); | |
cache_image.src = arguments[i]; | |
cache.push( cache_image ); | |
} | |
} |
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 | |
/** | |
* Add an image for preloading | |
* | |
* All images must be added using this function before the header is output | |
* | |
* @param mixed $img Either a string path, or a WP attachment object (the guid will be used) | |
* @return void | |
**/ | |
function pilau_add_image_for_preloading( $img ) { | |
global $pilau_preload_images; | |
if ( ! isset( $pilau_preload_images ) ) { | |
$pilau_preload_images = array(); | |
} | |
if ( is_object( $img ) && property_exists( $img , 'guid' ) ) { | |
$pilau_preload_images[] = $img->guid; | |
} else if ( is_string( $img ) ) { | |
$pilau_preload_images[] = $img; | |
} | |
} | |
/** | |
* Set up images for preloading | |
**/ | |
add_action( 'wp_head', 'pilau_images_preload', 100 ); | |
function pilau_images_preload() { | |
global $pilau_preload_images; | |
if ( isset( $pilau_preload_images ) && ! empty( $pilau_preload_images) ) { | |
?> | |
<script type="text/javascript"> | |
pilau_preload_images( "<?php echo implode( '", "', $pilau_preload_images ); ?>" ); | |
</script> | |
<?php | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://wordpress.org/plugins/preload-images/
this one help which same code based a plugin.