javascript - 使用 `document.currentScript.ownerDocument.createElement` 创建的图像(从 <link> 导入的 HTML)永远不会加载

标签 javascript google-chrome web-component custom-element html5-import

这是一个在给定图像网址的情况下返回图像宽度的函数:

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"> 的元素在附加到主文档之前不会加载。

来自HTML Imports tutorial :

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 postthat 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/

相关文章:

javascript - 在不重新加载页面的情况下停止 JavaScript

google-chrome - 将 Chrome 中的 console.log 保存到文件中

javascript - 使用影子根来隐藏爬虫数据

javascript - 如何在javascript中创建一个元素并向其传递参数?

web-component - 如何使用嵌套组件创建和样式化 3 个自定义元素?

javascript - 在其他地方单击时菜单应该消失

javascript - 如何在 Holder.js 图像中使用 Bootstrap Glyphicons

javascript - 如何在 AngularJS MD 中使用 <md-progress-linear>?

javascript - 在 XSLT 中使用变量应用模板

css - Chrome 溢出 :auto scrolls body when using trackpad