简体   繁体   English

Random 尝试获取图像的 naturalHeight 和 naturalWidth 失败

[英]Random fails trying to get the naturalHeight and naturalWidth of an image

I have some simple code where I check an image's width and height, and if it's not >= 120x90, it gets a visibility: hidden put on it.我有一些简单的代码可以检查图像的宽度和高度,如果它不是>= 120x90,它会得到visibility: hidden放在它上面。

$(".video-thumbnail").each(function() {
    var width = $(this).prop("naturalWidth");
    var height = $(this).prop("naturalHeight");

    if (width <= 120 && height <= 90) {
        $(this).css("visibility", "hidden");
    }
});

The problem is this randomly fails on some page reloads (see edit below).问题是这在某些页面重新加载时随机失败(请参阅下面的编辑)。

I think it may be a caching or browser loading delay issue.我认为这可能是缓存或浏览器加载延迟问题。

EDIT编辑

Confirmed sequence of events to reproduce:确认要重现的事件序列:

  1. Images are cached in browser图像缓存在浏览器中
  2. Modify HTML source修改HTML源码
  3. Navigate to page (not reload)导航到页面(不重新加载)

Any suggestions to run this more reliably?有什么建议可以更可靠地运行吗? Maybe force the browser to download the image file?也许强制浏览器下载图像文件? Not sure what that would look like.不知道那会是什么样子。

A more reliable solution would be to use the HTMLImageElement.decode() that returns a promise which is resolved once the full-resolution image is ready for use, an example of this is below:更可靠的解决方案是使用返回 promise 的HTMLImageElement.decode() ,一旦全分辨率图像可供使用,该函数就会被解析,示例如下:

 $(".video-thumbnail").each(function () { this.decode().then(() => { var width = $(this).prop("naturalWidth"); var height = $(this).prop("naturalHeight"); if (width <= 120 && height <= 90) { $(this).css("visibility", "hidden"); } }).catch((encodingError) => { // Do something with the error. }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img src="https://picsum.photos/121/91" class="video-thumbnail"> <img src="https://picsum.photos/121/91" class="video-thumbnail"> <img src="https://picsum.photos/119/89" class="video-thumbnail"> <img src="https://picsum.photos/121/91" class="video-thumbnail">

Posting an alternative method that also works as well as the one marked correct for my future reference:发布另一种方法,该方法与标记为正确的方法一样有效,以供我将来参考:

$(window).on("load", function() {
    $(".video-thumbnail").each(function() {
        var width = $(this).prop("naturalWidth");
        var height = $(this).prop("naturalHeight");

        if (width <= 120 && height <= 90) {
            $(this).css("visibility", "hidden");
        }
    });
});

Calling $(window).on("load"... first is the only change. Sometimes images were not loaded with my original code.调用$(window).on("load"... first 是唯一的变化。有时图像没有用我的原始代码加载。

Sources:资料来源:

Curious if there are any performance differences between this and the code in the answer marked correct.好奇这与答案中标记为正确的代码之间是否存在任何性能差异。 Behaviors seem to be identical.行为似乎是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM