Preloading images with JavaScript

后端 未结 14 1228
太阳男子
太阳男子 2020-11-22 03:17

Is the function I wrote below enough to preload images in most, if not all, browsers commonly used today?

function preloadImage(url)
{
    var img=new Image(         


        
14条回答
  •  执念已碎
    2020-11-22 03:50

    Working solution as of 2020

    Most answers on this post no longer work - (atleast on Firefox)

    Here's my solution:

    var cache = document.createElement("CACHE");
    cache.style = "position:absolute;z-index:-1000;opacity:0;";
    document.body.appendChild(cache);
    function preloadImage(url) {
        var img = new Image();
        img.src = url;
        img.style = "position:absolute";
        cache.appendChild(img);
    }
    

    Usage:

    preloadImage("example.com/yourimage.png");
    

    Obviously is not a "defined" element, so you could use a

    if you wanted to.

    Use this in your CSS, instead of applying the style attribute:

    cache {
        position: absolute;
        z-index: -1000;
        opacity: 0;
    }
    
    cache image {
        position: absolute;
    }
    

    If you have tested this, please leave a comment.

    Notes:

    • Do NOT apply display: none; to cache - this will not load the image.
    • Don't resize the image element, as this will also affect the quality of the loaded image when you come to use it.
    • Setting position: absolute to the image is necessary, as the image elements will eventually make it's way outside of the viewport - causing them to not load, and affect performance.

    UPDATE

    While above solution works, here's a small update I made to structure it nicely:

    (This also now accepts multiple images in one function)

    var cache = document.createElement("CACHE");
    document.body.appendChild(cache);
    function preloadImage() {
        for (var i=0; i

    Preview:

    Notes:

    • Try not to keep too many images preloaded at the same time (this can cause major performance issues) - I got around this by hiding images, which I knew wasn't going to be visible during certain events. Then, of course, show them again when I needed it.

提交回复
热议问题