tgwtdt
tgwtdt

Reputation: 362

javascript - How to store images on memory and load them from memory insteaId of cache?

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.

Upvotes: 3

Views: 7410

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51957

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"/>

Upvotes: 5

Related Questions