Home > Back-end >  Random fails trying to get the naturalHeight and naturalWidth of an image
Random fails trying to get the naturalHeight and naturalWidth of an image

Time:09-27

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.

$(".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
  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.

CodePudding user response:

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:

$(".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" >
<img src="https://picsum.photos/121/91" >
<img src="https://picsum.photos/119/89" >
<img src="https://picsum.photos/121/91" >

CodePudding user response:

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.

Sources:

Curious if there are any performance differences between this and the code in the answer marked correct. Behaviors seem to be identical.

  • Related