Advertisement
Guest User

Untitled

a guest
Feb 24th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. /*
  2. A very inefficient but with best browser support way would be to check if the
  3. clientBoundingRect of the image is currently inside the viewport or not on every
  4. scroll event, damn! it's costly!
  5. */
  6.  
  7. /*
  8.  
  9. Let's say the images in HTML are:
  10.  
  11. <img data-src="someimage1.png" class="lazy-image">
  12. <img data-src="someimage2.png" class="lazy-image">
  13. <img data-src="someimage3.png" class="lazy-image">
  14. <img data-src="someimage4.png" class="lazy-image">
  15. <img data-src="someimage5.png" class="lazy-image">
  16.  
  17. */
  18.  
  19. /*
  20. Then the following javaSscript code
  21. */
  22. (function() {
  23. document.addEventListener('DOMContentLoaded', () => {
  24. let debouncedLazyLoad = null;
  25. function lazyLoad() {
  26. if(debouncedLazyLoad) {
  27. clearTimeout(debouncedLazyLoad);
  28. }
  29. debouncedLazyLoad = setTimeout(() => {
  30. const images = document.querySelectorAll('.lazy-image');
  31. /**
  32. Foreach image we need to check if it's TOP is less than page's height (This means
  33. the current immediate bottom)
  34. */
  35. const pageCurrentBottom = window.innerHeight;
  36. images.forEach((img) => {
  37. const imgTop = img.getBoundingClientRect().top;
  38. if(imgTop < pageCurrentBottom) {
  39. img.src = img.dataset.src;
  40. img.classList.remove("lazy-image");
  41. }
  42. }, 200);
  43. });
  44. }
  45. document.addEventListener('scroll', lazyLoad);
  46. });
  47. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement