lazyload.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. (function(v, undefined) {
  2. 'use strict';
  3. // lazy loading
  4. var observer;
  5. if ( 'IntersectionObserver' in window ) {
  6. observer = new IntersectionObserver( function( changes ) {
  7. changes.forEach( function( change ) {
  8. if ( change.intersectionRatio > 0 || change.isIntersecting ) {
  9. showImage( change.target );
  10. observer.unobserve(change.target);
  11. }
  12. });
  13. }, {
  14. rootMargin: '200px',
  15. });
  16. }
  17. function onImageLoad() {
  18. /* jshint validthis: true */
  19. this.removeEventListener( 'load', onImageLoad );
  20. // this.dispatchEvent( new Event( 'vamtamlazyloaded', { bubbles: true } ) );
  21. requestAnimationFrame( function() {
  22. if ( ! ( this.classList.contains( 'vamtam-lazyload-noparent' ) ) && this.parentElement ) {
  23. this.parentElement.classList.add( 'image-loaded' );
  24. } else {
  25. this.classList.add( 'image-loaded' );
  26. }
  27. }.bind( this ) );
  28. }
  29. function showImage( image ) {
  30. var srcset = image.dataset.srcset;
  31. if ( srcset ) {
  32. requestAnimationFrame( function() {
  33. image.addEventListener( 'load', onImageLoad );
  34. image.srcset = srcset;
  35. } );
  36. delete image.dataset.srcset;
  37. } else {
  38. onImageLoad.call( image );
  39. }
  40. }
  41. // Either observe the images, or load immediately if IntersectionObserver doesn't exist
  42. function addElements() {
  43. var images = document.querySelectorAll('img[data-srcset]');
  44. var i;
  45. if ( observer ) {
  46. for ( i = 0; i < images.length; i++ ) {
  47. if ( ! ( 'vamtamLazyLoaded' in images[i] ) ) {
  48. images[i].vamtamLazyLoaded = true;
  49. observer.observe( images[i] );
  50. }
  51. }
  52. } else {
  53. for ( i = 0; i < images.length; i++ ) {
  54. if ( ! ( 'vamtamLazyLoaded' in images[i] ) ) {
  55. images[i].vamtamLazyLoaded = true;
  56. showImage( images[i] );
  57. }
  58. }
  59. }
  60. var otherImages = document.querySelectorAll('.vamtam-responsive-wrapper:not(.image-loaded) img:not([srcset])');
  61. for ( i = 0; i< otherImages.length; i++ ) {
  62. if ( ! ( 'vamtamLazyLoaded' in otherImages[i] ) ) {
  63. otherImages[i].vamtamLazyLoaded = true;
  64. showImage( otherImages[i] );
  65. }
  66. }
  67. }
  68. document.addEventListener('DOMContentLoaded', function() {
  69. var mutationObserver = new MutationObserver( addElements );
  70. mutationObserver.observe( document.body, {
  71. childList: true,
  72. subtree: true
  73. } );
  74. addElements();
  75. });
  76. })( window.VAMTAM );