Skip to content

Instantly share code, notes, and snippets.

@dimsemenov
Last active February 18, 2018 17:34
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dimsemenov/5382856 to your computer and use it in GitHub Desktop.
Save dimsemenov/5382856 to your computer and use it in GitHub Desktop.
I was looking for a way to get an image size with JavaScript before it's completely loaded. It's useful, for example, when you want to display it progressively. I've figured out that we can just fire an interval that will run until an image has defined width. Here is how it works:
// detect if naturalWidth property is supported
// getting it is much faster than getComputedStyle()
var supportsNatural = ( "naturalWidth" in (new Image()) ),
imagePath = 'image.jpg',
interval,
hasSize,
onHasSize = function() {
if(hasSize) return;
var naturalWidth = supportsNatural ? img[0].naturalWidth : img.width();
var naturalHeight = supportsNatural ? img[0].naturalHeight : img.height();
clearInterval(interval);
hasSize = true;
},
onLoaded = function() {
onHasSize();
},
onError = function() {
onHasSize();
},
checkSize = function() {
if(supportsNatural) {
if(img[0].naturalWidth > 0) {
onHasSize();
}
} else {
// some browsers will return height of an empty image about 20-40px
// just to be sure we check for 50
if(img.width() > 50) {
onHasSize();
}
}
},
img = $('<img/>')
.on('load', onLoaded)
.on('error', onError)
.attr('src', imagePath)
.appendTo(someContainer);
interval = setInterval(checkSize, 100);
checkSize();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment