Skip to content

Instantly share code, notes, and snippets.

@bob-lee
Last active November 24, 2017 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bob-lee/c95c84088491ff74cd2819654272b599 to your computer and use it in GitHub Desktop.
Save bob-lee/c95c84088491ff74cd2819654272b599 to your computer and use it in GitHub Desktop.
image.service setup for IntersectionObserver
const INTERSECT_PAGESIZE = 2;
@Injectable()
export class ImageService {
list: any[] = [];
intersectionObserver: IntersectionObserver;
intersectionRatio: number;
elementToObserve: Element;
private _indexToObserve: number; // only to grow from 0 as scrolling down
get indexToObserve() { return this._indexToObserve; }
set indexToObserve(value) {
const len = this.list.length;
if (!value || value <= this._indexToObserve || value >= len) {
return;
}
this._indexToObserve = value;
// update 'toLoad' to load more images
for (let i = 0; i < INTERSECT_PAGESIZE; i++) {
const index = this._indexToObserve + i;
if (index === len) { return };
this.list[index].toLoad = true;
}
}
constructor(private http: Http) {
try {
this.intersectionObserver = new IntersectionObserver(entries => {
const entry = entries[0];
const currentRatio = this.intersectionRatio;
const newRatio = entry.intersectionRatio;
const boundingClientRect = entry.boundingClientRect;
const scrollingDown = currentRatio !== undefined && newRatio < currentRatio &&
boundingClientRect.bottom < boundingClientRect.height;
this.intersectionRatio = newRatio;
if (scrollingDown) {
const i = this.indexToObserve + INTERSECT_PAGESIZE;
this.unobserve();
this.indexToObserve = i;
console.info(`${currentRatio} -> ${newRatio} [${i}]`);
}
}, { threshold: [ 0, 0.25, 0.5, 0.75, 1 ]});
} catch (e) {
console.error(`failed to create IntersectionObserver:`, e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment