Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress image preloading
/**
* 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 );
}
}
<?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
}
}
@rvpatel

This comment has been minimized.

Copy link

@rvpatel rvpatel commented Jan 12, 2021

https://wordpress.org/plugins/preload-images/
this one help which same code based a plugin.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment