Last active
January 6, 2023 18:27
-
-
Save ahmadthedev/349ebf5ed30ca48067540fd5f3537afc to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
/** | |
* 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