Last active
November 24, 2017 21:54
-
-
Save bob-lee/c95c84088491ff74cd2819654272b599 to your computer and use it in GitHub Desktop.
image.service setup for IntersectionObserver
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
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