Vanilla web-component structure

我的梦境 提交于 2019-11-28 00:27:04

There are 2 main methods to get the template from the imported document:

1. From the the import property of the <link> element

The <link rel=import> elements own an import property that contains the imported document. You can perform a querySelector call on it to fetch the <template>:

var doc = document.querySelector( 'link[href$="x-foo-from-template.html"]').import
var template = doc.querySelector( 'template' )

Then import the template in the custom element (or in its Shadow DOM) using either importNode() or cloneNode().


2. Form the ownerDocument property of currentScript

When a script is parsed, the global value document.currentScript references the script being parsed, and therefore its propery ownerDocument is a reference to the document that owns the script. You can perform a querySelector call on it:

var template = document.currentScript.ownerDocument.querySelector( 'template' )

Note: the currentScript value is set temporarily, so it won't work any more in subsequent calls, like connectedCallback() or attachedCallback(), so you'll have to memorize it in a persistent variable at parse time, to reuse it later when needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!