使用“document.currentScript.ownerDocument.createElement”创建的图像(从 <link> 中导入 HTML)从不加载
Images created using `document.currentScript.ownerDocument.createElement` (from within <link> imported HTML) never load
给定图像的 url:
,这是一个 returns 图像宽度的函数
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
引用 <link>
[=42= 的文档对象,document.createElement("img")
方法 将不起作用 ] 导入。
看看this example which imports this html。注意控制台输出:
"Starting..."
512
512
并且从不输出最终的 512
然后 "Finished."
,就像它(表面上)应该的那样。那是因为 imgEl
的 onload
事件永远不会触发;如果图像是使用 document.currentScript.ownerDocument.createElement
创建的,则该图像永远不会加载。我在 Chrome 69.
中测试过这个
这是预期的行为还是错误?如果无法使用 <link>
的 document
创建图像,它至少应该抛出一个错误吗?
这是正常行为。
导入文档 <link rel="import">
中 src
属性 <img>
元素中引用的图像在附加到主文档后才会加载。
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 的主要函数的参数传递 or .
( function( ownerDocument ) {
//...
if( method === "document.currentScript.ownerDocument.createElement") {
imgEl = ownerDocument.createElement("img")
var imgOK = document.adoptNode( imgEl )
}
//...
} ) ( document.currentScript.ownerDocument )
给定图像的 url:
,这是一个 returns 图像宽度的函数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
引用 <link>
[=42= 的文档对象,document.createElement("img")
方法 将不起作用 ] 导入。
看看this example which imports this html。注意控制台输出:
"Starting..."
512
512
并且从不输出最终的 512
然后 "Finished."
,就像它(表面上)应该的那样。那是因为 imgEl
的 onload
事件永远不会触发;如果图像是使用 document.currentScript.ownerDocument.createElement
创建的,则该图像永远不会加载。我在 Chrome 69.
这是预期的行为还是错误?如果无法使用 <link>
的 document
创建图像,它至少应该抛出一个错误吗?
这是正常行为。
导入文档 <link rel="import">
中 src
属性 <img>
元素中引用的图像在附加到主文档后才会加载。
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 的主要函数的参数传递
( function( ownerDocument ) {
//...
if( method === "document.currentScript.ownerDocument.createElement") {
imgEl = ownerDocument.createElement("img")
var imgOK = document.adoptNode( imgEl )
}
//...
} ) ( document.currentScript.ownerDocument )