Created
February 29, 2016 19:38
-
-
Save fernandofleury/f81616112ab06ef8ff56 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import throttle from '../utils/throttle'; | |
export default (($) => { | |
const NAME = 'lazyload'; | |
const DEFAULTS = { | |
throttle: 1000, | |
offset: 200 | |
}; | |
class LazyLoad { | |
constructor(element, options) { | |
options = $.extend({}, DEFAULTS, options || {}); | |
this._element = element; | |
this._options = options; | |
this.listeners(); | |
this.checkVisiblePlaceholders(); | |
} | |
listeners() { | |
this.onScrollHandler = throttle(this.onScroll.bind(this), this._options.throttle); | |
$(window).on('scroll', this.onScrollHandler); | |
} | |
onScroll() { | |
return this._element.length ? this.checkVisiblePlaceholders() : $(window).off('scroll', this.onScrollHandler); | |
} | |
checkVisiblePlaceholders() { | |
this.windowHeight = $(window).height(); | |
this.windowWidth = $(window).width(); | |
Array.prototype.forEach.call(this._element, this.checkPlaceholder.bind(this)); | |
} | |
checkPlaceholder(placeholder) { | |
if (this.isPlaceholderVisible(placeholder)) { | |
this.renderImage(placeholder); | |
this.removeFromArray(this._element, placeholder); | |
} | |
} | |
isPlaceholderVisible(placeholder) { | |
return placeholder.getBoundingClientRect().top <= (this.windowHeight + this._options.offset); | |
} | |
removeFromArray(array, item) { | |
let index = Array.prototype.indexOf.call(array, item); | |
Array.prototype.splice.call(array, index); | |
} | |
renderImage(placeholder) { | |
placeholder.parentNode.replaceChild(this.createImage(placeholder), placeholder); | |
} | |
createImage(placeholder) { | |
let image = document.createElement('img'); | |
this.parseAttributes(image, placeholder.attributes); | |
if (let breakpoints = placeholder.getAttribute('data-srcset')) { | |
this.parseBreakpoints(image, breakpoints); | |
return image; | |
} | |
image.src = placeholder.getAttribute('data-src'); | |
return image; | |
} | |
parseAttributes(image, attributes) { | |
Array.prototype.forEach.call(attributes, (attr) => { | |
if (attr.name !== 'data-lazy' || attr.name !== 'data-src') { | |
image.setAttribute(attr.name, attr.value); | |
} | |
}); | |
} | |
parseBreakpoints(image, breakpoints) { | |
} | |
destroy() { | |
$(window).off('scroll', this.onScrollHandler); | |
} | |
} | |
return LazyLoad; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment