Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

javascript - Vanilla web-component structure

I am looking into structuring vanilla web-components. I have previously used Polymer and like the fact that you can have the template, styles and JavaScript in one file for your component. I want to achieve this with 'vanilla' web components if possible but can't work out how. I've taken the code from here and added it to a file which I am using as follows:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Component test</title>

    <link rel="import" href="x-foo-from-template.html">
  </head>
  <body>
    <x-foo-from-template></x-foo-from-template>
  </body>
</html>

This fails because when we try to select the template it does not exist because at that point the template is not in the DOM (right?).

Is there any way to achieve this? I personally prefer this approach to creating the HTML in the JavaScript using document.createElement.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...