IntersectionObserver simplified
Checkout the main interserver
package.
With yarn
:
yarn add interserver-svelte
With npm
:
npm install --save interserver-svelte
The createInterserver
function takes the same options as the interserver
function (top
, right
, bottom
, left
and once
).
<script>
import createInterserver from 'interserver-svelte';
let container;
const intersecting = createInterserver(() => container);
$: if ($intersecting) {
console.log("Now you see me!");
} else {
console.log("Oh, the darkness...");
}
</script>
<div bind:this={container}>
...
</div>
You can build a LazyImage
component, that only requests an image, when it is approaching the viewport:
<!-- LazyImage.svelte -->
<script>
import createInterserver from 'interserver-svelte';
export let alt = '';
export let src = '';
export let srscet = null;
let container;
const intersecting = createInterserver(() => container, {
once: true,
top: 50,
right: 50,
bottom: 50,
left: 50,
});
$: src = $intersecting ? src : null;
$: srcset = $intersecting ? srcset : null;
</script>
<img {...$$props} {src} {srcset} {alt} bind:this={container} />
MIT