Guest User

Untitled

a guest
Nov 14th, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. 'use strict';
  2. import createImageObject from './createImageObject';
  3. import { throttle } from 'throttle-debounce';
  4.  
  5. const initDLoad = parameters => {
  6. const options = parameters;
  7.  
  8. /**
  9. * Set default classes if none is given in the parameters;
  10. */
  11.  
  12. setDefaultOptions(parameters, options);
  13.  
  14. const lazyElements = Array.prototype.slice.call(document.getElementsByClassName(options.className));
  15.  
  16. /**
  17. * Throw error if there no elements, but classname exits;
  18. */
  19. if (!lazyElements.length) { throw 'No elements are found'; };
  20. setImageSources(lazyElements, options.loadedClass);
  21.  
  22. /**
  23. * Check if there still images after init
  24. * if so, add eventlistener;
  25. */
  26. if (!lazyElements.length) { return false; };
  27.  
  28. window.addEventListener('scroll', throttle(50, () => {
  29. setImageSources(lazyElements, options.loadedClass);
  30. }));
  31.  
  32. window.addEventListener('touchmove', throttle(50, () => {
  33. setImageSources(lazyElements, options.loadedClass);
  34. }));
  35. };
  36.  
  37. /**
  38. * Set Default options
  39. */
  40. const setDefaultOptions = (parameters, options) => {
  41.  
  42. if (!parameters['className']) {
  43. options.className="lazy-load";
  44. }
  45.  
  46. if (!parameters['loadedClass']) {
  47. options.loadedClass="lazy-loaded";
  48. }
  49.  
  50. if (!options.loadedClass || !options.className) {
  51. throw Error('Either the default class name or loaded class name failed to set.');
  52. }
  53.  
  54. return options;
  55. }
  56.  
  57. /**
  58. * Check if element is in view
  59. */
  60. const isElementInView = (el) => {
  61. const rect = el.getBoundingClientRect();
  62. return (
  63. rect.top >= 0
  64. && rect.bottom <= (window.innerHeight + el.clientHeight || document.documentElement.clientHeight + el.clientHeight)
  65. );
  66. };
  67.  
  68. /**
  69. * Create image instance
  70. */
  71. const setImageSources = (elements, className) => {
  72. for (let i = elements.length -1; i >= 0; i--) {
  73. const el = elements[i];
  74. if(isElementInView(el)) {
  75. new createImageObject(el, className);
  76. removeItemFromArray(el, elements);
  77. }
  78. }
  79. }
  80.  
  81. const removeItemFromArray = (el, elements) => {
  82. const i = elements.indexOf(el);
  83. if (i > -1) {
  84. elements.splice(i, 1);
  85. };
  86.  
  87. return elements;
  88. }
  89.  
  90. export default initDLoad;
Add Comment
Please, Sign In to add comment