Skip to content

Instantly share code, notes, and snippets.

@keithdevon
Last active December 22, 2017 00:52
Show Gist options
  • Save keithdevon/d1676bd62eeef6e1b2df to your computer and use it in GitHub Desktop.
Save keithdevon/d1676bd62eeef6e1b2df to your computer and use it in GitHub Desktop.
Lazy loading WordPress images
// make sure this script is called in the footer of your document
function inView(image){
var $image = jQuery(image),
view_top = jQuery(window).scrollTop() - 300,
view_bottom = view_top + jQuery(window).height() + 600,
height = $image.height(),
_top = $image.offset().top,
_bottom = _top + height;
return height > 0 && _top <= view_bottom && _bottom >= view_top;
}
function maybeLoad(images) {
images.each(function(i, image){
if(image.hasAttribute('data-lazy') && inView(image)) {
image.src = image.getAttribute('data-lazy');
image.removeAttribute('data-lazy');
//image.trigger('lazy-load');
}
})
}
var images = jQuery('img'),
didScroll = false;
jQuery(window).on('load', function(){
maybeLoad(images);
});
jQuery(window).scroll(function() {
didScroll = true;
});
setInterval(function() {
if ( didScroll ) {
didScroll = false;
// Check your page position and then
// Load in more results
maybeLoad(images);
}
}, 250);
<?php
// change 'image_size' to your custom size
// change 'holding.jpg' to your holding image
$thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id,'image_size', true);
?>
<img src="<?php bloginfo('stylesheet_directory'); ?>/holding.jpg" data-lazy="<?php echo $thumb_url[0];?>"/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment