Jquery: Preload an image on request with a callback function?

后端 未结 1 813
太阳男子
太阳男子 2021-01-23 17:39

I\'m helping out a friend with a website he\'s developing and we are having trouble with preloading images on request. Basically, when the user clicks on a thumbnail of the prod

相关标签:
1条回答
  • 2021-01-23 18:21

    Preloading images can be done using following code:

    $('<img/'>,{'src': image_source});
    

    As we can also use the load event on images, we can have an callback when one image is done; To solve the issue to fire a callback after four images is loaded, we would need some kind of counter.

    Perhaps following code might work (untested):

    var preloadImages = function(image_links, callback) {
      var self = this;
      // assume image_links is an array here
      var count = image_links.length;
      $.each( image_links, function(){
        $('<img/>', {
          'src': this, // url
          'load': function(){
            if( --count == 0 ) {
              callback.apply(self);
            }
          }
        });
      });      
    }
    
    0 讨论(0)
提交回复
热议问题