-->

How to access custom element from within a linked

2019-07-28 20:59发布

问题:

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

回答1:

You cannot do that as explained in this thread: The currentScript property will return null.

Instead you should load the script outside of the <template>, and invoke a function defined in the script from your custom element callbacks connectedCallback() or constructor().



回答2:

You must access currentScript outside of the component. I use this:

var frag = (document.currentScript||document._currentScript).ownerDocument.querySelector('template').content;

I use (document.currentScript||document._currentScript) to handle polyfills.

Then in your constructor you would use:

const instance = frag.cloneNode(true);

At this point frag is a document-fragment and can contain any number of children. All of these will be replicated by the call to cloneNode so that each instance of your Web Component has its own copy of DOM.