使用`document.currentScript.ownerDocument.createElement`创建的图像(来自内部 导入HTML)从不加载

问题描述 投票:1回答:1

这是一个返回图像宽度的函数,给定图像的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;
}

它工作正常。如果我们使用new Image()而不是document.createElement("img"),它(当然)也有效。

但是,如果document.createElement("img")引用document html导入的文档对象,则<link>方法不起作用。

看看进口this examplethis html。请注意控制台输出:

"Starting..."
512
512

并且永远不会输出最终的512然后"Finished.",就像它(看似)应该。那是因为onloadimgEl事件从未发生过;如果图像是用document.currentScript.ownerDocument.createElement创建的,则图像永远不会加载。我在Chrome 69中测试了这个。

这是预期的行为,还是一个错误?如果不能使用<link>document创建图像,它不应该至少抛出错误吗?

javascript google-chrome web-component custom-element html5-import
1个回答
2
投票

这是正常的行为。

在导入文档中使用src<img>属性<link rel="import">元素中引用的图像在被附加到主文档之前不会加载。

来自HTML Imports tutorial

在您调用其服务之前,请将内容视为惰性内容。 [...]

除非你将它的内容附加到DOM,否则它是一个无操作。事实上,直接在导入文档中“执行”的唯一事情是<script>

您可以使用qazxsw poi将其用于主文档。

另请注意,在您的示例中,您应该将导入的文档引用作为simple-test.html主函数的参数传递,原因可以解释为document.apendNode()in this post

that post
© www.soinside.com 2019 - 2024. All rights reserved.