Search code examples
javascriptpreload

If I preload an image using javascript will it then be loaded when I use it in a <img> tag?


I had an issue with small images loading very slowly so I figured I should try to preload it to the browser cache. I looked it up and found numerous ways to asynchronously preload the images but two things remained unclear. Let's say I have an array of images file names (assume each element is the correct full path)

const images = ['img1.png','img2.png','img3.png']

I preload the images using what I've learned from Preloading Images with JavaScript

function preLoad(){
  images.forEach(img => {
    const myImage = new Image()
    myImage.onload = (img) => myImage.src = img
  })
}
preload()

Note that I didn't store any of the images objects in a variable or an array. After the process is done, are the images cached and ready to use just by referencing the file name? For example if I tried to

document.getElementById('image-container').innerHTML = `<img src="${images[0]}" alt="${images[0]}>`

Will it show the image immediately? And since this method doesn't use any of the asynchronous methods (callback, promises, async/await), How can I know the process is done and the images are ready to be used?


Solution

  • I had a similar issue once and have posted it here. I used <link rel="preload" as="image" href="cards/PNG/2C.png"> to achieve preloading.

    I imagine your JavaScript function does the same. If so what happens is that the browser loads all the images before it displays the page and therefore it can display the images without interruption.

    To be able to check if that's really what's happening "Inspect" your page and in the sources tab you should be able to see all the files the browser has loaded up including your images and it uses the same file hierarchy as you did in your code.