Skip to content

Instantly share code, notes, and snippets.

View AsafAgranat's full-sized avatar

Asaf Limi Agranat AsafAgranat

View GitHub Profile
@dimsemenov
dimsemenov / get-image-size.js
Last active February 18, 2018 17:34
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();