Preloading images with JavaScript

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

    Yes this will work, however browsers will limit(between 4-8) the actual calls and thus not cache/preload all desired images.

    A better way to do this is to call onload before using the image like so:

    function (imageUrls, index) {  
        var img = new Image();
    
        img.onload = function () {
            console.log('isCached: ' + isCached(imageUrls[index]));
            *DoSomething..*
    
        img.src = imageUrls[index]
    }
    
    function isCached(imgUrl) {
        var img = new Image();
        img.src = imgUrl;
        return img.complete || (img .width + img .height) > 0;
    }
    

提交回复
热议问题