Skip to content

Instantly share code, notes, and snippets.

@mi-ca
Last active September 21, 2020 13:20
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 mi-ca/5adf0cd22051cdce1176bbd1e913e4e0 to your computer and use it in GitHub Desktop.
Save mi-ca/5adf0cd22051cdce1176bbd1e913e4e0 to your computer and use it in GitHub Desktop.
<?php
function getLazyLoadImg($id,$lb=true,$size='large',$title=false){
$lbOpen=$lbClose='';
$tiny = wp_get_attachment_image_src( $id, 'thumbnail' ); // récup la miniature
$largeimg = wp_get_attachment_image_src( $id, $size); // récup la taille souhaité
$image_alt = get_post_meta($id, '_wp_attachment_image_alt', TRUE);
if(!$largeimg){ // si pas de taille demandé
if(wp_get_attachment_image_src( $id, 'large' )){ // fallback vers large
getLazyLoadImg($id,$lb,'large',$title);
}else if(wp_get_attachment_image_src( $id, 'medium' )){ // fallback ver medium
getLazyLoadImg($id,$lb,'medium',$title);
}else{
return false;
}
}
if(!$image_alt){
$image_alt=get_the_title($id);
}
$title_attr='';
if($title){
$title_attr=' title="'.$title.'"';
}
if($lb===true){
$bigImg = wp_get_attachment_image_src( $id, '2048x2048' ); // récup la grande (si lightbox)
if($bigImg){
$lbOpen='<a class="lb"'.$title_attr.' href="'.$bigImg[0].'">';
$lbClose='</a>';
}
}
$img.='<img class="lazyload" src="'.$tiny[0].'" data-src="'.$largeimg[0].'" width="'.$largeimg[1].'" height="'.$largeimg[2].'" alt="'.$image_alt.'">';
return $lbOpen.$img.$lbClose;
}
/* Lazyload
* lazyload images with .lazyload class > add .loaded when loaded ;)
* > SRC : https://css-tricks.com/a-few-functional-uses-for-intersection-observer-to-know-when-an-element-is-in-view/#use-case-1-lazy-loading-images
* > https://codepen.io/rpsthecoder/pen/pByZjR
* > author : Preethi _> https://github.com/rpsthecoder
*/
if(!!window.IntersectionObserver){
let observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if(entry.isIntersecting){
entry.target.src = entry.target.dataset.src;
observer.unobserve(entry.target);
entry.target.classList.add('loaded');
}
});//>forEach
}, {rootMargin: "0px 0px 0px 0px"});
document.querySelectorAll('img.lazyload').forEach(img => { observer.observe(img) });
}//> #Lazyload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment