Last active
October 30, 2024 20:54
-
-
Save keithdevon/d1676bd62eeef6e1b2df to your computer and use it in GitHub Desktop.
Lazy loading WordPress 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
// 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); |
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 | |
// 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