Skip to content

Instantly share code, notes, and snippets.

@pavosdijital
Forked from gyrus/preload-images.js
Created March 3, 2021 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavosdijital/3a4ca2d573ba7d08b6ebb0e4c543296b to your computer and use it in GitHub Desktop.
Save pavosdijital/3a4ca2d573ba7d08b6ebb0e4c543296b to your computer and use it in GitHub Desktop.
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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment