如何知道文档中的所有图像何时加载Javascript? [英] How to know when all images from document did load in Javascript?

查看:111
本文介绍了如何知道文档中的所有图像何时加载Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有Ruby On Rails的ajax函数演示< div> 内容我正在演示部分进入 div ,我想知道什么时候加载所有图片,因为现在我有了这个:

I'm realoading a <div> content with an ajax function with Ruby On Rails i'm realoading a partial into a div and i want to know hot to know when all images have loaded because now i have this:

$(document).ready(function(){
    $("img").load(function(){
        alert("ok?");
    });
});

但有了这个,我继续为这个部分的每个图像获得一个alet ....

but with this i keep getting an alet for every image on this partial....

我不知道iuf有一个选择器,如 $(allimgs)或类似的东西,我该怎么做在所有图像被加载时捕获?

i don't know iuf there's a selector like $(allimgs) or something like that, what do i have to do to catch when all images are loaded?

非常感谢。

推荐答案

如果您希望确保所有图像的加载没有错误,您必须自己滚动。如果没有,你可以使用已经显示的.load,当浏览器加载资源时会激活。

If you wish to ensure that all images loaded without errors you have to roll your own. If not you can use .load like already shown which will fire when the browser is done loading assets.

要自己滚动,请执行以下操作:

To roll your own, do something like this:

 $(document).ready(function(){
    var imgs = $("img"), cnt = imgs.length;

    imgs
    .load(function(){
      if(!--cnt) {
        /* all images loaded */
      }
    })
    .error(function() { /* whoops an image failed to load */});
  });

这篇关于如何知道文档中的所有图像何时加载Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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