Guest User

Untitled

a guest
May 26th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. // Lazy-load background images
  2. var elements = document.querySelectorAll('.lazy-background');
  3. var bg_images = document.querySelectorAll('[data-src]');
  4. var config = {
  5. rootMargin: '0px 0px 50px 0px',
  6. threshold: 0
  7. };
  8.  
  9. var loaded = 0;
  10.  
  11. // If intersection observer is not supported (IE), load images immediately
  12. if (!('IntersectionObserver' in window)) {
  13. for (var i = 0; i < elements.length; i++) {
  14. preloadImage(elements[i]);
  15. }
  16. } else {
  17. // If intersection observer is supported
  18. var observer = new IntersectionObserver(function (entries, self) {
  19. entries.forEach(function(entry){
  20. if (entry.isIntersecting) {
  21. preloadImage(entry.target);
  22. // Stop watching and load the image
  23. self.unobserve(entry.target);
  24. }
  25. });
  26. }, config);
  27.  
  28. bg_images.forEach(function(image) {
  29. observer.observe(image);
  30. });
  31. }
  32.  
  33. function preloadImage(section) {
  34. var src = section.getAttribute('data-src');
  35. if (!src) { return; }
  36.  
  37. // If img tag change src, else add backgroundImage style
  38. if (section.tagName === 'IMG') {
  39. section.src = src;
  40. } else {
  41. section.style.backgroundImage = 'url(' + src + ')';
  42. }
  43. }
Add Comment
Please, Sign In to add comment