<!doctype html>
<link rel="import" href="component.html">
<compo-nent></compo-nent>
<script>
console.log(1)
</script>
<compo-nent></compo-nent>
[component.html]
<template>
<p>p</p>
</template>
<script>
customElements.define("compo-nent", class extends HTMLElement {
constructor() {
console.log("start")
super()
const t = document.currentScript.ownerDocument.querySelector("template")
this.attachShadow({ mode: "open" }).append(t.content.cloneNode(true))
console.log("end")
}
})
</script>
main.html のページを開くと
start
end
1
start
Uncaught TypeError: Cannot read property 'ownerDocument' of null
script タグが実行されると document.currentScript が null になる
constructor のような後から実行されるところで取得しないほうがいい
script タグ実行時に変数に入れておくと大丈夫
<template>
<p>p</p>
</template>
<script>
{
const doc = document.currentScript.ownerDocument
customElements.define("compo-nent", class extends HTMLElement {
constructor() {
console.log("start")
super()
const t = doc.querySelector("template")
this.attachShadow({ mode: "open" }).append(t.content.cloneNode(true))
console.log("end")
}
})
}
</script>