获取图像宽度的最早事件

Earliest event to get an image's width

本文关键字:事件 图像 获取      更新时间:2023-09-26

我有一些JavaScript来居中图像,如果它们超过阈值宽度,则在页面上<object>。它还检查某些类是否尚未手动应用。

$('img,object').bind('load', function() {
    w = $(this).width();
    if (w > 400 && !( $(this).hasClass('inlineimage') | $(this).parent().hasClass('inlineimage') ))
        $(this).css('margin', '10px ' + (parseInt((800-w)/2)-30) +'px');
});

这很可怕,但这背后的意义最初是相当理智的。CMS 并不容易指定对齐方式,并且开发它以允许这会占用其他工作的大量时间。客户端黑客有效。

它唯一的问题是JS等到整个图像加载完毕。显然,这意味着在较慢的网络上,页面加载,图像开始加载,一段时间后图像捕捉到位。丑。

但是浏览器似乎在开始下载图像后立即知道图像的宽度。我真的很想参与这个事件并拼凑这个视觉错误。

当然,如果有CSS的方式来解决这个问题,我也愿意接受。

在支持它的浏览器中,您可以轮询自然维度:

var interval = setInterval( function() {
    if( img.naturalWidth ) {
        clearInterval(interval);
        console.log( "Natural available: "+ (new Date - now );
        console.log( img.naturalWidth, img.naturalHeight );
    }
}, 0 );

在未缓存图像的演示中,我得到:

Natural available: 782
62 71 
Loaded: 827 

因此,实际尺寸在加载事件前 50 毫秒可用。不幸的是,在IE中,readystate "loading"不能保证真实的尺寸。

在每次测试之前更改图像的查询字符串,以确保未缓存。

以下是关于自然维度的链接:http://www.whatwg.org/specs/web-apps/current-work/multipage/embedded-content-1.html#dom-img-naturalwidth

var span = document.getElementById('span'); // The parent span
var check = function (){
    if(span.offsetWidth > 0){
        console.log('Width while loading', span.offsetWidth);
    }
    else{
       setTimeout(check, 100);
    }
};
check();

演示。这应该在控制台中显示首先加载时的宽度,然后在加载后显示宽度。只要图像未缓存即可。(如果演示不适用于某人,请尝试将图像 URL 的hoo部分更改为其他任何内容)

为了在最新的浏览器上仍然有效,我拼凑了一个尽力而为的蛮力。它在两次尝试之间等待 500 毫秒,并检查图像以查看当前运行是否与上次尝试的宽度相同。

只要图像的宽度在连续两次传递中相同,我们就运行居中代码。

这使用数组来跟踪事情,因此我们不会经常强奸 DOM,也不会查询不适用的项目(因为它们已经被处理或排除了)。


attempts = 0;
arr = [];
$.each($('img,object').not('inlineimage'), function(){
    arr.push([this, -2, $(this).width()]);
});
checkImgs = function() {
    attempts++;
    newarr = []
    $.each(arr, function(){
        if ($(this[0]).parent().hasClass('inlineimage'))
            return;
        w = $(this[0]).width();
        this[1] = this[2];
        this[2] = w;
        if (this[1] != this[2])
            return newarr.push(this);
        // We know this image is loaded enough now - we can do things!
        if (w >= 400)
            $(this[0]).css('margin', '10px ' + (parseInt((800-w)/2)-30) +'px');
    });
    arr = newarr;
    if (arr.length && attempts < 6)
        setTimeout(checkImgs, 500);
}
setTimeout(checkImgs, 500);

它并不漂亮,但它似乎既能高效工作(CPU 被我早期的一些尝试重创),又能快速工作(缓存图像在 500 毫秒内弹到位)。