0

I want to preload my images but don't necessarily want to append them to the DOM. If I preload an image will it effectively be precached?

My understanding is that caching works by reference to the src of an image. From playing around it seems as if preloading in order to precache does indeed work. However, I'm not sure; this may be unreliable or have some negative effect on performance.

I'm using the image constructor to preload.

const img = new Image();
img.src = imageArray[i].url;
leto
  • 489
  • 4
  • 18
  • Possible duplicate of https://stackoverflow.com/questions/287750/how-do-i-pre-cache-images-for-quick-viewing-with-javascript – Alireza Nov 04 '19 at 20:24

1 Answers1

1

Yes, it does indeed work.

function preloadImage(url){
    const img = new Image();
    img.src = imageArray[i].url;
}

However, there is a couple of approach. For example, delaying preloading until after the page loads:

function preloader() {
    if (document.images) {
        var img1 = new Image();
        var img2 = new Image();
        var img3 = new Image();

        img1.src = "http://url/image-001.jpg";
        img2.src = "http://url/image-002.jpg";
        img3.src = "http://url/image-003.jpg";
    }
}
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}
addLoadEvent(preloader);
Ömürcan Cengiz
  • 2,085
  • 3
  • 22
  • 28