Skip to content

Instantly share code, notes, and snippets.

@MD4
Last active March 25, 2019 15:01
Show Gist options
  • Save MD4/38462924f6a78a8f301d721954d99a2f to your computer and use it in GitHub Desktop.
Save MD4/38462924f6a78a8f301d721954d99a2f to your computer and use it in GitHub Desktop.
const preFetchImageSize = (url, checkInterval = 10) => new Promise((resolve, reject) => {
const image = new Image();
image.src = url;
image.onerror = reject;
const interval = setInterval(() => {
if (image.width + image.naturalWidth) {
clearInterval(interval);
resolve({
width: image.naturalWidth || image.width,
height: image.naturalHeight || image.height,
});
image.src = '';
}
}, checkInterval);
});
preFetchImageSize('https://i.imgur.com/xFnVjMV.jpg')
.then(console.log)
.catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment