javascript - 什么是 "document.currentScript"和 "ownerDocument"?

标签 javascript html dom web-component html5-template

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

<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 元素引入的。

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

最佳答案

_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将为您提供对导入文档的引用(使用 <link rel='import'> ),其中当前 <script>正在运行,<template> 在哪里已定义。

参见 this SO answer (和 this one)以获取有关此主题的更多详细信息。

关于javascript - 什么是 "document.currentScript"和 "ownerDocument"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47419825/

相关文章:

javascript - lodash 映射返回对象数组

javascript - 如何使用 MikroORM 插入对象图?

php - 表格每一行的非法字符串偏移量 'Data_length'/'Index_length'

jquery - 使用 html 和 css 创建带有座位号的场景表示的最佳方法

javascript - XMLHttpRequest.send(file) 的 Fetch API 等价物是什么?

javascript - 切换/暂停 JavaScript 滚动功能

javascript - 使用正则表达式验证域名

javascript - jQuery Mobile - 哈希处理以及后续的 jQuery.show() 问题

javascript - document.write() 造成了什么损害?

dom - 在不直接操作 DOM 的情况下绘制 d3 轴