lazy.js 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. // LAZY LODING JS
  2. // CREDIT: Rahul Nanwani
  3. // https://css-tricks.com/the-complete-guide-to-lazy-loading-images/
  4. document.addEventListener("DOMContentLoaded", function() {
  5. var lazyloadImages = document.querySelectorAll("img.lazy");
  6. var lazyloadThrottleTimeout;
  7. function lazyload () {
  8. if(lazyloadThrottleTimeout) {
  9. clearTimeout(lazyloadThrottleTimeout);
  10. }
  11. lazyloadThrottleTimeout = setTimeout(function() {
  12. var scrollTop = window.pageYOffset;
  13. lazyloadImages.forEach(function(img) {
  14. if(img.offsetTop < (window.innerHeight + scrollTop)) {
  15. img.src = img.dataset.src;
  16. img.classList.remove('lazy');
  17. }
  18. });
  19. if(lazyloadImages.length == 0) {
  20. document.removeEventListener("scroll", lazyload);
  21. window.removeEventListener("resize", lazyload);
  22. window.removeEventListener("orientationChange", lazyload);
  23. }
  24. }, 20);
  25. }
  26. document.addEventListener("scroll", lazyload);
  27. window.addEventListener("resize", lazyload);
  28. window.addEventListener("orientationChange", lazyload);
  29. });