Last active
September 21, 2020 13:20
-
-
Save mi-ca/5adf0cd22051cdce1176bbd1e913e4e0 to your computer and use it in GitHub Desktop.
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 | |
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; | |
} |
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
/* 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