lazy-loading.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Lazy loading! Roll your own. Woot.
  2. // This file includes a 8unch of fall8acks and stuff like that, and is written
  3. // with fairly Olden JavaScript(TM), so as to work on pretty much any 8rowser
  4. // with JS ena8led. (If it's disa8led, there are gener8ted <noscript> tags to
  5. // work there.)
  6. var observer;
  7. function loadImage(image) {
  8. image.src = image.dataset.original;
  9. }
  10. function lazyLoad(elements) {
  11. for (var i = 0; i < elements.length; i++) {
  12. var item = elements[i];
  13. if (item.intersectionRatio > 0) {
  14. observer.unobserve(item.target);
  15. loadImage(item.target);
  16. }
  17. }
  18. }
  19. function lazyLoadMain() {
  20. // This is a live HTMLCollection! We can't iter8te over it normally 'cuz
  21. // we'd 8e mutating its value just 8y interacting with the DOM elements it
  22. // contains. A while loop works just fine, even though you'd think reading
  23. // over this code that this would 8e an infinitely hanging loop. It isn't!
  24. var elements = document.getElementsByClassName('js-hide');
  25. while (elements.length) {
  26. elements[0].classList.remove('js-hide');
  27. }
  28. var lazyElements = document.getElementsByClassName('lazy');
  29. if (window.IntersectionObserver) {
  30. observer = new IntersectionObserver(lazyLoad, {
  31. rootMargin: '200px',
  32. threshold: 1.0
  33. });
  34. for (var i = 0; i < lazyElements.length; i++) {
  35. observer.observe(lazyElements[i]);
  36. }
  37. } else {
  38. for (var i = 0; i < lazyElements.length; i++) {
  39. var element = lazyElements[i];
  40. var original = element.getAttribute('data-original');
  41. element.setAttribute('src', original);
  42. }
  43. }
  44. }
  45. document.addEventListener('DOMContentLoaded', lazyLoadMain);