如何在 <script type="module"> 中获得 document.currentScript.ownerDocument?
How to get document.currentScript.ownerDocument in <script type="module">?
如何在脚本 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>
如何在脚本 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>