3

What I'm doing right now is using the following function to preload images to cache. I was wondering if it is possible to load them from memory for even faster load time.

function preloadImage (done, i) {
    if (!i) { i = 1; }

    var img = new Image();
    img.onloadend = function () {
        if (this.height == 0) { return done(); }
        preloadImage(done, i + 1);
    };
    img.src = "images/" + i;
}

preloadImage(function () { console.log('images loaded'); });

What I want to do is to load an array of image() elements with javascript and then show them in a slideshow.

tgwtdt
  • 362
  • 2
  • 15
  • You could try to use the localStorage. In that example the localStorage is used to pass an image to the next page: you could try to use it for your needed: https://stackoverflow.com/questions/19183180/how-to-save-an-image-to-localstorage-and-display-it-on-the-next-page – debe Feb 08 '18 at 12:01
  • I want to use memory not disk. – tgwtdt Feb 08 '18 at 12:12
  • 1
    Thanks for asking another question, and good luck with your image animation project. – Patrick Roberts Feb 08 '18 at 15:37

1 Answers1

5

Here's how to put an Image object directly into the DOM without having to reload with src after prefetching:

// wait 2 seconds
setTimeout(() => {
  // preload image
  var image = new Image();

  image.addEventListener('load', function () {
    // place into DOM
    // assert(this === image);
    document.querySelector('img').replaceWith(this);
  });

  image.src = 'https://www.w3schools.com/w3css/img_lights.jpg';
}, 2000);
<img src="https://www.w3schools.com/howto/img_fjords.jpg"/>
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153