Preloading images with JavaScript

后端 未结 14 1062
太阳男子
太阳男子 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:52

    This approach is a little more elaborate. Here you store all preloaded images in a container, may be a div. And after you could show the images or move it within the DOM to the correct position.

    function preloadImg(containerId, imgUrl, imageId) {
        var i = document.createElement('img'); // or new Image()
        i.id = imageId;
        i.onload = function() {
             var container = document.getElementById(containerId);
             container.appendChild(this);
        };
        i.src = imgUrl;
    }
    

    Try it here, I have also added few comments

提交回复
热议问题