0

Do you have to insert an image into the DOM to get its dimensions?

Yanick and many others say yes, add the img to the dom off screen to get its dimensions (after it is loaded).

Alex, Nickf and others say no, you can create an img element that is not added to the dom. Its image will then be loaded and sized.

Which opinion is right for "modern" browsers? Are there any tests which cover this question. Is this behavior by design for the browsers?

ADDED: I'm looking for a source / reference that confirms this behavior. I already have code examples a plenty.

Community
  • 1
  • 1
Larry K
  • 47,808
  • 15
  • 87
  • 140
  • No you can create img element and it will have it's dimension – Voonic Dec 01 '13 at 18:31
  • The code in my answer shows that you can create an image and retrieve its width (or any other property) without adding it into the DOM. How much clearer would you like it? – dav1dsm1th Dec 03 '13 at 11:19

2 Answers2

0

There's no need to add the element to the DOM to get those properties from it - just create the <img> element and the dimensions will be accessible in JS.

steve
  • 2,469
  • 1
  • 23
  • 30
  • Ok, how do you know this? Which browsers have you tested this behavior in? Is the behavior by design or a quirk. Eg it looks like hidden imgs also get loaded. Will that change some day in some browsers? – Larry K Dec 01 '13 at 19:29
0

Try this:-

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title>answer</title>
    </head>
    <body>
        <script>
            var img = new Image;
            img.onload = function(){alert(img.width);};
            img.src = "image.png";
        </script>
    </body>
</html>

Which will alert the image width (assuming there is an image called image.png in the same folder as the file containint this htlm).

dav1dsm1th
  • 1,687
  • 2
  • 20
  • 24
  • Ok, how do you know this? Which browsers have you tested this behavior in? Is the behavior by design or a quirk. Eg it looks like hidden imgs also get loaded. Will that change some day in some browsers? – Larry K Dec 03 '13 at 18:41
  • I know this because I've tested it in IE11, Chrome 31.0.1650.57m and FireFox 25.0.1. I assume it's not a quirk as it would be statistically unlikely that the development teams of all three browsers had included the same quirk in their codebases. You're question, "Do you have to insert an image into the DOM to get its dimensions?", does not ask if hidden imgs get loaded. Will it change? Probably. It's an infinite universe and there is an awful lot of time left to go. – dav1dsm1th Dec 03 '13 at 22:06
  • Thank you for the testing. I gave you the check. – Larry K Dec 05 '13 at 07:09