【问题标题】:How to get document.currentScript.ownerDocument in <script type="module">?如何在 <script type="module"> 中获取 document.currentScript.ownerDocument?
【发布时间】:2017-07-21 04:11:39
【问题描述】:

如何在脚本 type="module" 中获取 ownerDocument?

<template>
  text
</template>
<script type="module">
  let owner = document.currentScript.ownerDocument // is null
  
  // But i need get <template>
  
  let tpl = owner.querySelector('template')
</script>

【问题讨论】:

  • 在 FF 上为我工作。不得不修复 &lt;/template&gt; 结束标签。
  • @Kaiido 它不适用于 Chrome 和其他浏览器
  • 确实刚刚在金丝雀中尝试过,但它不起作用。我没有关于谁在这里的消息来源,但是 FF 在 DOMContentLoaded 事件之前执行 module 脚本,而 chrome 在之后执行它......但最后,在这个例子中,owner === document
  • 所以在测试了更多的金丝雀之后,我倾向于在他们如何处理defer 脚​​本方面出现一个错误。它应该在之前 DOMContentLoaded 触发,但失败了。因此此时,currentScriptnull
  • 我还没有找到如何实现你想要的。但是,我可以说所描述的行为是正确的。实际上,Edge 填写了相反的错误报告(设置了 currentScript)。 developer.microsoft.com/en-us/microsoft-edge/platform/issues/…

标签: html ecmascript-6 web-component es6-modules


【解决方案1】:

规范明确指出,当使用&lt;script type="module"&gt; 时,document.currentScript 属性在执行期间设置为nullSee spec under "execute a script block".

如果使用src 属性,这当然是显而易见的。源无法知道它将由脚本标记而不是导入语句(或两者)调用。内联模块时总是有一个脚本标签,但我猜他们想让体验保持一致。

如果您的文档实际上是仍可作为全局使用的 window.document。否则,如果您仍希望将脚本作为模块加载,您有两种选择:

  • 不是最漂亮的;在模块上方创建一个全局并存储模板。

    <script type="text/javascript">
    window.myTemplates = ((ns) => {
      const owner = window.document.currentScript.ownerDocument;
      ns.fancyButton = owner.querySelector("template");
      return ns;
    })(window.myTemplates || {});
    </script>
    
    <script type="module">
    const tpl = window.myTemplates.fancyButton;
    // ...
    </script>
    
  • 不要将模板写成 HTML 模板,而是写成 ES/JS 模板。您的编辑器可能不支持突出显示文字 HTML,标签的 linting 是个问题。

    <script type="module">
    const tpl = window.document.createElement("template");
    tpl.innerHTML = `
      <strong>example</strong>
      <span style="background-color: rgba(127,127,127,0.6);">text</span>
    `;
    // ...
    </script>
    

【讨论】:

    猜你喜欢
    • 2022-09-30
    • 1970-01-01
    • 2018-07-18
    • 2017-06-17
    • 1970-01-01
    • 2018-06-07
    • 2020-10-17
    • 2023-03-16
    相关资源
    最近更新 更多