Created
March 9, 2019 12:01
-
-
Save jesperlandberg/e58f41cc79d80c87c732aae9c1aae232 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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