Skip to content

Instantly share code, notes, and snippets.

@ahmadthedev
Last active January 6, 2023 18:27
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 ahmadthedev/349ebf5ed30ca48067540fd5f3537afc to your computer and use it in GitHub Desktop.
Save ahmadthedev/349ebf5ed30ca48067540fd5f3537afc to your computer and use it in GitHub Desktop.
<?php
/**
* Lazy Load All Images
*
* To Exclude, simply add this attr to img html: loading="not_lazy"
*
* @param string $html Post thumbnail HTML
*
* @return string Filtered post image HTML.
*/
add_filter( 'post_thumbnail_html', 'atdev_add_lazy_load_to_imgs', 10, 1 );
add_filter( 'wp_get_attachment_image', 'atdev_add_lazy_load_to_imgs', 10, 1 );
function atdev_add_lazy_load_to_imgs( $html ) {
if( ! is_admin() && ! str_contains(strtolower($html), 'loading="not_lazy"') ){
$html = str_replace(
' src=',
' loading="lazy" data-lazy src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkqAcAAIUAgUW0RjgAAAAASUVORK5CYII=" data-src=',
$html
);
}
return $html;
}
?>
<script>
/**
* Lazy Load Images using Intersection Observer
*
*/
var observer = new IntersectionObserver(onIntersect);
document.querySelectorAll("[data-lazy]").forEach((img) => {
observer.observe(img);
});
function onIntersect(entries) {
entries.forEach((entry) => {
if (entry.target.getAttribute("loading") == 'not_lazy' || entry.target.getAttribute("data-processed") || !entry.isIntersecting)
return true;
entry.target.setAttribute("src", entry.target.getAttribute("data-src"));
entry.target.setAttribute("data-processed", true);
});
}
/**
* (Trying to) Not lazy load above the fold images
*/
document.addEventListener('DOMContentLoaded',() => {
win_height = window.innerHeight;
imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
// At least 20 px above the fold
if( imgs[i].getAttribute("loading") != 'not_lazy' && (imgs[i].offsetTop+20) < win_height ){
imgs[i].setAttribute("src", imgs[i].getAttribute("data-src"));
imgs[i].setAttribute("data-processed", true);
}
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment