Skip to content
This repository has been archived by the owner on Jan 15, 2020. It is now read-only.

Commit

Permalink
Uses unobserve to stop watching and disconnects IO
Browse files Browse the repository at this point in the history
Thanks to Birkir Guðjónsson and Abinash Mohapatra for the suggestion! :)
  • Loading branch information
paullewis committed Mar 10, 2017
1 parent 05ffd98 commit 8b52486
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions src/client/scripts/helpers/lazy-load-images.js
Expand Up @@ -25,19 +25,20 @@ class LazyLoadImages {
return ('IntersectionObserver' in window);
}

static get THRESHOLD () {
return 0.01;
}

static get HANDLED_CLASS () {
return 'js-lazy-image--handled';
}

static get THRESHOLD () {
return 0.01;
}

static init () {
if (this._instance) {
this._instance._disconnect();
}

this._count = 0;
this._instance = new LazyLoadImages();
}

Expand All @@ -54,6 +55,7 @@ class LazyLoadImages {
return;
}

this._count = images.length;
this._onIntersection = this._onIntersection.bind(this);
this._observer = new IntersectionObserver(this._onIntersection, config);
images.forEach(image => {
Expand All @@ -79,13 +81,16 @@ class LazyLoadImages {
return;
}

if (entry.target.classList.contains(LazyLoadImages.HANDLED_CLASS)) {
return;
}

entry.target.classList.add('js-lazy-image--handled');
this._count--;
this._observer.unobserve(entry.target);
this._preloadImage(entry.target);
});

if (this._count > 0) {
return;
}

this._observer.disconnect();
}

_preloadImage (image) {
Expand All @@ -107,6 +112,8 @@ class LazyLoadImages {
return;
}

// Prevent this from being lazy loaded a second time.
img.classList.add(LazyLoadImages.HANDLED_CLASS);
el.style.backgroundImage = `url(${src})`;
el.classList.add('fade-in');
}
Expand Down

0 comments on commit 8b52486

Please sign in to comment.