html - 如何获取 <script type ="module"> 中的 document.currentScript.ownerDocument?

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

如何在脚本 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>

最佳答案

规范明确指出,当使用 <script type="module">document.currentScript属性设置为 null在执行期间。 See 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>
    

关于html - 如何获取 &lt;script type ="module"> 中的 document.currentScript.ownerDocument?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45228821/

相关文章:

javascript - 在 JavaScript 中制作原型(prototype)

javascript - NodeJS 认为我在重复参数名称,但其实我没有

web-component - AMP HTML 是否允许非官方的自定义元素

javascript - 在嵌套的 Polymer 自定义元素中访问 JavaScript 方法

JQuery 'Sortable' 在 wordpress 插件中不工作

php - 表单问题(在表中提前关闭)

javascript - 粗箭头函数 (=>) 的语法,在主体周围使用或不使用 {}

javascript - Web 组件(JavaScript 原生)可以注册在 HTML 主体的末尾吗?

javascript - 了解 <a href ="#!"

javascript - 用变量传播 prevState