If I had a script like this
<template id="x-foo-from-template">
<script src="/js/main.js"></script>
</template>
<script>
customElements.define('my-header', class extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({mode: 'open'});
const t = document.currentScript.ownerDocument.querySelector('#x-foo-from-template');
const instance = t.content.cloneNode(true);
shadowRoot.appendChild(instance);
// set up title
var title = this.getAttribute("title");
var div = document.createElement("div");
div.innerText = title;
shadowRoot.appendChild(div);
}
});
</script>
From within main.js
how can I access the custom element which is equivalent to this
in the constructor()
?
Thanks
You cannot do that as explained in this thread: The
currentScript
property will returnnull
.Instead you should load the script outside of the
<template>
, and invoke a function defined in the script from your custom element callbacksconnectedCallback()
orconstructor()
.You must access
currentScript
outside of the component. I use this:I use
(document.currentScript||document._currentScript)
to handle polyfills.Then in your constructor you would use:
At this point
frag
is adocument-fragment
and can contain any number of children. All of these will be replicated by the call tocloneNode
so that each instance of your Web Component has its own copy of DOM.