Gentlemen, in this example, as you can see, I get what I want, but on my computer, by no means ... Picture with the result. Any idea why this is? By the way, an example on a computer, plain HTML on the desktop ...

And in the chome and FF the same result

enter image description here

var img1 = document.getElementById('img1'); console.log(img1.naturalWidth) 
 <img width="100" height="100" id="img1" class="img" src="https://www.1zoom.ru/big2/34/322924-alexfas01.jpg" alt="A"> 

  • Maybe the picture does not have time to load? - Dmytryk
  • Dmytryk, you are a genius)))) exactly .... setTimeout helped - Air
  • do not setTimeout . it will be different at different internet speeds. - Raz Galstyan
  • @RazGalstyan, I know, in this case, setTimeout used to identify the problem, not to solve it - Air
  • Incidentally, the same is true when the pictures are not loaded from the network, but are in the folder on the desktop too - Air

3 answers 3

You just need to use onload .

 document.addEventListener('DOMContentLoaded', function (){ var img1 = document.getElementById('img1'); img1.onload = function(){ console.log(img1.naturalWidth) }; }); 
 <img width="100" height="100" id="img1" class="img" src="http://www.visitcalifornia.com/sites/default/files/styles/welcome_image/public/VCW_D_Bigsur_T2_CC_BigSurBeach_Miller-1280x642.jpg" alt="A"> 

  • Your answer is more adequate ...)))) - Air
  • one
    A question for general development: why .onload after DOMContentLoaded (I would like to understand) - Vlad Vityuk
  • one
    Everything, understood, read the documentation :) - Vlad Vityuk
  • @VladVityuk That's good - Raz Galstyan

The onload event on window is triggered when the entire page is loaded, including the resources on it — styles, images, frames, and so on.

 window.onload = function(){ var img1 = document.getElementById('img1'); console.log(img1.naturalWidth) } 
 <img width="100" height="100" id="img1" class="img" src="https://www.1zoom.ru/big2/34/322924-alexfas01.jpg" alt="A"> 

ps edited

  • Again for the first time issued 0 - Raz Galstyan
  • Vlad Vityuk, you have the same result in your console as on my computer)))) - Air
  • Yes, tupanul, load here does not fit. - Vlad Vityuk
  • And again, I have 0 after you changed the answer - Raz Galstyan
  • Re-read, this method works in 90% of cases. Fix it again - Vlad Vityuk

It turned out, everything is simple .... The picture does not have time to load .... Special thanks to Dmytryk ....

 var img1 = document.getElementById('img1'); setTimeout(function() { console.log(img1.naturalWidth) }, 5000) 
 <img width="100" height="100" id="img1" class="img" src="https://www.1zoom.ru/big2/34/322924-alexfas01.jpg" alt="A">