Jquery:使用回调函数根据请求预加载图像? [英] Jquery: Preload an image on request with a callback function?

查看:150
本文介绍了Jquery:使用回调函数根据请求预加载图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在帮助他正在开发网站的朋友,我们在按要求预加载图片时遇到问题。基本上,当用户点击产品的缩略图时,< div> 向下滑动,其中包括滚动的大图像转盘。总共有大约20MB的图像可以加载(如果你全部完成),所以在页面加载上预加载它们不是一个选项。

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 product a <div> slides down that includes a scrolling carrousel of large images. In total there are about 20MB of images that could be loaded in (if you did them all) so preloading them on the page load would not be an option.

是否有一种我们可以调用javascript函数开始预加载大约4个图像的方法,然后当它完成时它有一个回调函数?

Is there a way that we could call a javascript function that begins to preload about 4 images and then when it's done it has a callback function?

谢谢!
P.S.我们在页面上使用jQuery ...

Thanks! P.S. We are using jQuery on the page...

推荐答案

可以使用以下代码完成预加载图像:

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);
        }
      }
    });
  });      
}

这篇关于Jquery:使用回调函数根据请求预加载图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆