Preloading images with JavaScript

后端 未结 14 1235
太阳男子
太阳男子 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条回答
  •  萌比男神i
    2020-11-22 03:58

    In my case it was useful to add a callback to your function for onload event:

    function preloadImage(url, callback)
    {
        var img=new Image();
        img.src=url;
        img.onload = callback;
    }
    

    And then wrap it for case of an array of URLs to images to be preloaded with callback on all is done: https://jsfiddle.net/4r0Luoy7/

    function preloadImages(urls, allImagesLoadedCallback){
        var loadedCounter = 0;
      var toBeLoadedNumber = urls.length;
      urls.forEach(function(url){
        preloadImage(url, function(){
            loadedCounter++;
                console.log('Number of loaded images: ' + loadedCounter);
          if(loadedCounter == toBeLoadedNumber){
            allImagesLoadedCallback();
          }
        });
      });
      function preloadImage(url, anImageLoadedCallback){
          var img = new Image();
          img.onload = anImageLoadedCallback;
          img.src = url;
      }
    }
    
    // Let's call it:
    preloadImages([
        '//upload.wikimedia.org/wikipedia/commons/d/da/Internet2.jpg',
      '//www.csee.umbc.edu/wp-content/uploads/2011/08/www.jpg'
    ], function(){
        console.log('All images were loaded');
    });
    

提交回复
热议问题