【问题标题】:What is "document.currentScript" and "ownerDocument"?什么是“document.currentScript”和“ownerDocument”?
【发布时间】:2017-11-21 18:06:56
【问题描述】:

我正在学习 Web 组件。要获取模板,我需要这样做:

<template>
  <div>The sky is blue</div>
</template>

<script>
    var tmpl = (document.currentScript||document._currentScript).ownerDocument.querySelector('template');

代替:

var tmpl = document.querySelector('template');

这部分我完全看不懂:(document.currentScript||document._currentScript).ownerDocument

currentScript 是什么,ownerDocument 是什么?什么目的?为什么它有效。请注意,我上面显示的模板代码是通过 link 元素拉入的。

注意,这与postarticle 有关。我只是想了解关键字,我没有任何特别的问题。

【问题讨论】:

    标签: javascript html dom web-component html5-template


    【解决方案1】:

    _currentScript 用于旧的 webcomponentsjs polyfill(版本 0.x)。现在,如果您使用 polyfill 版本 1.x,它始终是 undefined

    你应该只使用document.currentScript:

    <template>
      <div>The sky is blue</div>
    </template>
    
    <script>
        var tmpl = document.currentScript.ownerDocument.querySelector('template');
    </script>
    

    document.currentScript.ownerDocument 将为您提供对导入文档的引用(带有&lt;link rel='import'&gt;),当前&lt;script&gt; 正在其中运行,&lt;template&gt; 已在其中定义。

    有关此主题的更多详细信息,请参阅 this SO answer(和 this one)。

    【讨论】:

      【解决方案2】:

      从这里得到的定义: https://html.spec.whatwg.org/multipage/dom.html#dom-document-currentscript

      document.currentScript

      返回 当前正在执行的脚本元素或 SVG 脚本元素,只要该元素代表经典脚本即可。在可重入脚本执行的情况下,返回尚未完成执行的脚本中最近开始执行的脚本。

      如果 Document 当前未执行脚本或 SVG 脚本元素(例如,因为正在运行的脚本是事件处理程序或超时),或者当前执行的脚本或 SVG 脚本元素表示一个模块,则返回 null脚本。

      而且我相信 _currentScript 来自 Polyfill。

      对于 DOM 树中的任何内容,ownerDocument 将是 document,但对于 &lt;template&gt; 或通过 HTML 导入加载的文件,ownerDocument 将是不同的文档。这就是为什么 document.querySelector() 无法获取使用 HTML 导入加载的文件的 &lt;template&gt; 的原因。

      【讨论】:

      • 我可以在 Chrome 中使用 _currentScript 而无需任何 polyfill。我猜我的代码甚至没有达到由于空合并。无论如何,我仍然很难遵循正式的定义。
      • 我只知道我总是同时检查两者。也许我应该理解why,但是一旦我找到了如何让它工作,我就停止了寻找。 ;)。
      • 嘿,感谢您的帮助,您确实启动并运行了我的代码 =)
      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多