Skip to content

loadImage function

Daisho Komiyama edited this page Feb 24, 2023 · 4 revisions

When you see the image flickering on page load, as images take more time to be rendered than HTML elements, in such cases, you might want to wait till the image is completely loaded.

This function loadImage might be a help.

function loadImage(src) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = reject;
    img.src = src;
  });
}

Usage example;

The function loadDetails gets the details of a person and returns it. It works fine, but when the data is rendered in HTML, the image gets rendered last, and it creates a subtle flickering. We don't want that.

So we are going to change from this

// Person {
//   id: string
//   name: string
//   address: string
//   image: string  
// }

const loadDetails = async (person) => {
  const res = await fetch(`https://something/api/${person.id}.json`);
  return await res.json();
}

to this

const loadDetails = async (person) => {
  const res = await fetch(`https://something/api/${person.id}.json`);
  const details = await res.json();
  await loadImage(details.image); // new!
  return details;
}

And also, if you have some static assets, you can use loadImage by simply passing an image file path. We don't need await here because we're just kicking those off in the background.

(The example below is from SvelteKit)

onMount(() => {
  loadImage('/icons/logo.svg');
  loadImage('/icons/arrow.svg');
})

So by the time they are needed, they'll be instantly there since we've already loaded them.

That's it. Try to see if it works for you.

Clone this wiki locally