jQuery-检查何时加载图像? [英] JQuery - Check when image is loaded?

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

问题描述

加载图像后,我在解决问题上遇到了麻烦.

I am having a bit of trouble working out when an image has been loaded.

有人告诉我下面的功能可以工作,但是它什么也没做.

I have been told that the following function will work but it isn't doing anything.

$("#photos img:first").load(function (){
    alert("Image loaded!");
});

我的代码中没有错误.我脚本中的其他所有内容都很好.

There are no error's in my code. Everything else in my script works great.

我的HTML看起来像这样.

My HTML looks like this.

<div id="photos">
    <img src="../sample1.jpg" style="background-color:#000033" width="1" height="1" alt="Frog!"/>
    <img src="../sample2.jpg" style="background-color:#999999" width="1" height="1" alt="Zooey!"/>
</div>

我的JQuery函数是否错误?还应注意,可见性设置为隐藏.但是,即使可见,也不会发出警报.

Do I have the wrong JQuery function? It should also be noted that the visibility is set to hidden. However even when visible there is no alert.

有什么想法吗?

推荐答案

图像的load事件在加载时触发(doh!),更重要的是,如果不连接处理程序在加载之前,您的处理程序将不会被调用.浏览器将并行加载资源,因此您无法确定(即使在jQuery的ready事件中说页面的DOM已准备就绪)在代码运行时尚未加载图像.

The load event of an image is fired when it's loaded (doh!), and critically, if you don't hook up your handler before it loads, your handler won't get called. Browsers will load resources in parallel, so you can't be sure (even in jQuery's ready event saying the page's DOM is ready) that the image hasn't already been loaded when your code runs.

您可以使用图像对象的complete属性来了解它是否已经被加载,所以:

You can use the complete property of the image object to know whether it's already been loaded, so:

var firstPhoto = $("#photos img:first");
if (firstPhoto[0].complete) {
    // Already loaded, call the handler directly
    handler();
}
else {
    // Not loaded yet, register the handler
    firstPhoto.load(handler);
}
function handler() {
    alert("Image loaded!");
}

如果所涉及的浏览器确实实现了多线程加载,其中图像加载可能发生在与Javascript线程不同的线程上,那么甚至可能存在竞态条件.

There may even be a race condition in that, if the browser in question really implements multi-threaded loading where the image load may occur on a different thread than the Javascript thread.

当然,如果您的选择器将匹配多个图像,则需要进行处理;您的选择器看起来应该只匹配一个,所以...

Of course, if your selector will match multiple images, you'll need to handle that; your selector looks like it's supposed to match only one, so...

编辑,该版本可以处理多张图片,我认为可以处理任何非Java竞争条件(当然,目前存在 没有Java竞争条件; JavaScript本身是浏览器中的单线程[除非您使用新的网络工作者东西]):

Edit This version allows for multiple images, and I think it handles any non-Javascript race conditions (and of course, at present there are no Javascript race conditions; Javascript itself is single-threaded in browsers [unless you use the new web workers stuff]):

function onImageReady(selector, handler) {
    var list;

    // If given a string, use it as a selector; else use what we're given
    list = typeof selector === 'string' ? $(selector) : selector;

    // Hook up each image individually
    list.each(function(index, element) {
        if (element.complete) {
            // Already loaded, fire the handler (asynchronously)
            setTimeout(function() {
                fireHandler.call(element);
            }, 0); // Won't really be 0, but close
        }
        else {
            // Hook up the handler
            $(element).bind('load', fireHandler);
        }
    });

    function fireHandler(event) {
        // Unbind us if we were bound
        $(this).unbind('load', fireHandler);

        // Call the handler
        handler.call(this);
    }
}

// Usage:
onImageReady("#photos img:first");

一些注意事项:

  • 回调未获取event对象;您可以根据需要对其进行修改,但是当然,在图像已加载的情况下不会发生任何事件,因此实用性有限.
  • 您可能会使用one而不是bindunbind,但是我很清楚,我很偏执. :-)
  • The callback doesn't get the event object; you could modify it to do so if you liked, but of course, there'd be no event in the case where the image is already loaded, so it would be of limited utility.
  • You could probably use one instead of bind and unbind, but I like the clarity and I'm paranoid. :-)

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

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