如何在<script type =“ module”>中获取document.currentScript.ownerDocument?

Арт*_*щев 5 html web-component ecmascript-6 es6-modules

我如何在script 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>
Run Code Online (Sandbox Code Playgroud)

Tim*_*ist 6

该规范明确指出,当使用<script type="module">document.currentScript属性时,该属性设置为null在执行期间。请参阅“执行脚本块”下的规范

当然,如果使用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>
    
    Run Code Online (Sandbox Code Playgroud)
  • 不要将模板编写为 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>
    
    Run Code Online (Sandbox Code Playgroud)