这是一个在给定图像网址的情况下返回图像宽度的函数:
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;
}
效果很好。如果我们使用new Image()
,它也(当然)有效。而不是document.createElement("img")
.
但是,document.createElement("img")
方法不起作用如果 document
指的是 <link>
的文档对象html 导入。
看看this example其中进口this html 。请注意,控制台输出:
"Starting..."
512
512
并且从不输出最终的512
然后"Finished."
,就像(看起来)应该的那样。那是因为onload
事件imgEl
从不着火;如果图像是使用 document.currentScript.ownerDocument.createElement
创建的,则永远不会加载图像。我已经在 Chrome 69 中对此进行了测试。
这是预期行为还是错误?如果无法使用 <link>
创建图像,它至少应该抛出一个错误吗?的document
?
最佳答案
这是正常行为。
src
中引用的图像属性 <img>
导入文档中带有 <link rel="import">
的元素在附加到主文档之前不会加载。
Think of content as inert until you call upon its services. [...]
Unless you append it's content to the DOM, it's a no-op. In fact, the only thing that "executes" in the import document directly is
<script>
.
您可以使用 document.apendNode()
将其附加到主文档中.
另外,请注意,在您的示例中,您应该将导入的文档引用作为 simple-test.html 主函数的参数传递,原因如下 in this post或that post .
( function( ownerDocument ) {
//...
if( method === "document.currentScript.ownerDocument.createElement") {
imgEl = ownerDocument.createElement("img")
var imgOK = document.adoptNode( imgEl )
}
//...
} ) ( document.currentScript.ownerDocument )
关于javascript - 使用 `document.currentScript.ownerDocument.createElement` 创建的图像(从 <link> 导入的 HTML)永远不会加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52344788/