<!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?).
There are 2 main methods to get the template from the imported document:
1. From the the
import property of 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
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
2. Form the
ownerDocument property of
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' )
currentScript value is set temporarily, so it won't work any more in subsequent calls, like
attachedCallback(), so you'll have to memorize it in a persistent variable at parse time, to reuse it later when needed.
©2020 All rights reserved.