Skip to content

Instantly share code, notes, and snippets.

@jesperlandberg
Created March 9, 2019 12:01
Show Gist options
  • Select an option

  • Save jesperlandberg/e58f41cc79d80c87c732aae9c1aae232 to your computer and use it in GitHub Desktop.

Select an option

Save jesperlandberg/e58f41cc79d80c87c732aae9c1aae232 to your computer and use it in GitHub Desktop.
import bindAll from '../utils/bindAll'
class LazyLoad {
constructor(entries) {
bindAll(this, ['handle'])
this.images = entries
this.options = {
root: null,
rootMargin: '50% 50% 50% 50%',
threshold: [0, 0]
}
this.observer = new IntersectionObserver(this.handle, this.options)
this.init()
}
handle(entries, observer) {
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
this.loadImage(entry.target)
this.observer.unobserve(entry.target)
}
})
}
observe() {
this.images.forEach(img => {
this.observer.observe(img)
})
}
loadImage(target) {
const src = target.dataset.lazySrc
this.fetchImage(src).then(() => {
target.src = src
})
}
fetchImage(url) {
return new Promise((resolve, reject) => {
const image = new Image()
image.src = url
image.onload = resolve
image.onerror = reject
})
}
destroy() {
this.observer.disconnect()
this.observer = null
this.images = null
}
init() {
this.observe()
}
}
export default LazyLoad
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment