Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy load images in (svelte/sapper)

Tags:

svelte

What would be best way to do this kind of lazy loading in Sapper:

  1. Navigate to page containing image
  2. First download small image from src
  3. Start loading larger version from data-src and change that to src when ready
  4. Navigate to another page
  5. Come back to image page and have already loaded larger image there

If someone could help, I would be very happy :)

like image 815
bbbmazon Avatar asked Jan 29 '23 05:01

bbbmazon


1 Answers

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>
like image 158
Rich Harris Avatar answered Apr 01 '23 09:04

Rich Harris