Preloading images with JavaScript

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

    Yes. This should work on all major browsers.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 03:54
    const preloadImage = src => 
      new Promise(r => {
        const image = new Image()
        image.onload = r
        image.onerror = r
        image.src = src
      })
    
    
    // Preload an image
    await preloadImage('https://picsum.photos/100/100')
    
    // Preload a bunch of images in parallel 
    await Promise.all(images.map(x => preloadImage(x.src)))
    
    0 讨论(0)
  • 2020-11-22 03:57

    Here is my approach:

    var preloadImages = function (srcs, imgs, callback) {
        var img;
        var remaining = srcs.length;
        for (var i = 0; i < srcs.length; i++) {
            img = new Image;
            img.onload = function () {
                --remaining;
                if (remaining <= 0) {
                    callback();
                }
            };
            img.src = srcs[i];
            imgs.push(img);
        }
    };
    
    0 讨论(0)
  • 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');
    });
    
    0 讨论(0)
  • 2020-11-22 03:59

    You can move this code to index.html for preload images from any url

    <link rel="preload" href="https://via.placeholder.com/160" as="image">
    
    0 讨论(0)
提交回复
热议问题