What would be best way to do this kind of lazy loading in Sapper:
If someone could help, I would be very happy :)
You're looking for actions. These are functions that run when an element is added to the DOM, and return an object with a destroy
and (optional) update
method.
You could do something like this (interactive demo here):
<img
alt="random photo"
src="https://picsum.photos/100/50"
use:lazy="{src: 'https://picsum.photos/400/200'}"
>
<style>
img {
width: 400px;
height: 200px;
}
</style>
<script>
const loaded = new Map();
export default {
actions: {
lazy(node, data) {
if (loaded.has(data.src)) {
node.setAttribute('src', data.src);
} else {
// simulate slow loading network
setTimeout(() => {
const img = new Image();
img.src = data.src;
img.onload = () => {
loaded.set(data.src, img);
node.setAttribute('src', data.src);
};
}, 2000);
}
return {
destroy(){} // noop
};
}
}
};
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With