Skip to content

Commit 2e858fb

Browse files
koddssonkeithamus
andcommitted
Add a visible strategy
Co-authored-by: Keith Cirkel <keithamus@users.noreply.github.com>
1 parent f6489c9 commit 2e858fb

1 file changed

Lines changed: 27 additions & 1 deletion

File tree

src/lazy-define.ts

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,36 @@ const firstInteraction = new Promise<void>(resolve => {
2222
document.addEventListener('pointerdown', handler, listenerOptions)
2323
})
2424

25+
const visible = (tagName: string): Promise<void> =>
26+
new Promise<void>(resolve => {
27+
const observer = new IntersectionObserver(
28+
entries => {
29+
for (const entry of entries) {
30+
if (entry.isIntersecting) {
31+
resolve()
32+
observer.disconnect()
33+
return
34+
}
35+
}
36+
},
37+
{
38+
// Currently the threshold is set to 256px from the bottom of the viewport
39+
// with a threshold of 0.1. This means the element will not load until about
40+
// 2 keyboard-down-arrow presses away from being visible in the viewport,
41+
// giving us some time to fetch it before the contents are made visible
42+
rootMargin: '0px 0px 256px 0px',
43+
threshold: 0.01
44+
}
45+
)
46+
for (const el of document.querySelectorAll(tagName)) {
47+
observer.observe(el)
48+
}
49+
})
2550

2651
const strategies: Record<string, Strategy> = {
2752
ready: () => ready,
28-
firstInteraction: () => firstInteraction
53+
firstInteraction: () => firstInteraction,
54+
visible
2955
}
3056

3157
export function addStrategy(name: string, strategy: Strategy) {

0 commit comments

Comments
 (0)