Here's a function that returns the width of an image, given the image's url:
async function getImageWidthByUrl(imgUrl) {
const imgEl = document.createElement("img");
let untilImgLoaded = new Promise((resolve, reject) => {
imgEl.onload = resolve;
imgEl.onerror = reject;
});
imgEl.src = imgUrl;
await untilImgLoaded;
return imgEl.naturalWidth;
}
It works fine. It also (of course) works if we use new Image()
instead of document.createElement("img")
.
However, the document.createElement("img")
method doesn't work if document
refers to the document object of a <link>
html import.
Have a look at this example which imports this html. Notice that the console outputs:
"Starting..."
512
512
and never outputs the final 512
and then "Finished."
, like it (seemingly) should. That's because the onload
event of the imgEl
never fires; the image never loads if it was created with document.currentScript.ownerDocument.createElement
. I've tested this in Chrome 69.
Is this expected behaviour, or a bug? Shouldn't it at least throw an error if it's not possible to create an image using a <link>
's document
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…