我正在学习网络组件。要获取模板,我需要这样做:
<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
元素引入的。
最佳答案
_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/