Skip to content

Commit 96d19eb

Browse files
committed
Make Intersection Observer options configurable
Fixes #16
1 parent a520507 commit 96d19eb

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,22 @@ Because of how this package works, it is not possible to nest multiple root node
176176
</template>
177177
```
178178

179+
#### Intersection Obersver options
180+
181+
Internally the [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver) is used to determine if a component is visible or not. You can provide Intersection Observer options to the `when-visible` property to configure the Intersection Observer.
182+
183+
```html
184+
<template>
185+
<div class="MyComponent">
186+
<LazyHydrate when-visible="{ rootMargin: '100px' }">
187+
<ArticleFooter/>
188+
</LazyHydrate>
189+
</div>
190+
</template>
191+
```
192+
193+
For a list of possible options please [take a look at the Intersection Observer API documentation on MDN](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver).
194+
179195
## Benchmarks
180196

181197
### Without lazy hydration

src/LazyHydrate.js

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
const isServer = typeof window === `undefined`;
22
const isBrowser = !isServer;
3-
let observer = null;
43

5-
if (typeof IntersectionObserver !== `undefined`) {
6-
observer = new IntersectionObserver((entries) => {
4+
const observers = new Map();
5+
6+
function createObserver(options) {
7+
if (typeof IntersectionObserver === `undefined`) return null;
8+
9+
const optionKey = JSON.stringify(options);
10+
if (observers.has(optionKey)) return observers.get(optionKey);
11+
12+
const observer = new IntersectionObserver((entries) => {
713
entries.forEach((entry) => {
814
// Use `intersectionRatio` because of Edge 15's
915
// lack of support for `isIntersecting`.
@@ -13,7 +19,10 @@ if (typeof IntersectionObserver !== `undefined`) {
1319

1420
entry.target.parentElement.hydrate();
1521
});
16-
});
22+
}, options);
23+
observers.set(optionKey, observer);
24+
25+
return observer;
1726
}
1827

1928
export default {
@@ -36,7 +45,7 @@ export default {
3645
type: Boolean,
3746
},
3847
whenVisible: {
39-
type: Boolean,
48+
type: [Boolean, Object],
4049
},
4150
},
4251
data() {
@@ -101,6 +110,9 @@ export default {
101110
}
102111

103112
if (this.whenVisible) {
113+
const options = this.whenVisible === true ? {} : this.whenVisible;
114+
const observer = createObserver(options);
115+
104116
// If Intersection Observer API is not supported, hydrate immediately.
105117
if (!observer) {
106118
this.hydrate();

0 commit comments

Comments
 (0)