Jquery:使用回调函数根据请求预加载图像?

发布于 2024-09-03 14:56:15 字数 270 浏览 2 评论 0原文

我正在帮助一位朋友开发一个网站,但我们在根据请求预加载图像时遇到了问题。基本上,当用户单击产品的缩略图时,

会向下滑动,其中包含大图像的滚动轮播。总共大约有 20MB 的图像可以加载(如果您加载了全部),因此在页面加载时预加载它们不是一个选择。

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

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

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.

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?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天涯沦落人 2024-09-10 14:56:15

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

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

由于我们还可以在图像上使用 load 事件,因此我们可以在一张图像完成时进行回调;为了解决加载四个图像后触发回调的问题,我们需要某种计数器。

也许以下代码可能有效(未经测试):

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

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);
        }
      }
    });
  });      
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文