Re: [w3c/webcomponents] connectedCallback timing when the document parser creates custom elements (#551)

Hi everyone,
based on the recomendations from this and other posts, we have been able to get around this problem with the folowing steps:

- make sure the parent is connected (aka. trigger custom function in connectedCallback)
- the element or its parent have nextSibling (for the edge cases it should be checked if the parent elements have next siblings) 
OR the elements reacts on mutation observer with the requestAnimationFrame which gives us security that the DOM is parsed.

**Long story short:**
`/* jshint esversion:6 */
export function htmlCustomElement(self) {

    self.animationFrameIds = [];
    self.observeCount = 0;
    // determine if the children are already connected
    if (self.nextSibling || self.parentNode.nextSibling) {
        self.animationFrameIds.push(requestAnimationFrame(childrenParsedCallback.bind(self)));
    } else {
        self.mutationObserver = new MutationObserver(changes => {
            if (changes[0].type === "childList") {
                self.animationFrameIds.push(requestAnimationFrame(childrenParsedCallback.bind(self)));
            }
        });

        self.mutationObserver.observe(self, {
            childList: true,
        });

    }

    function childrenParsedCallback() {
        this.animationFrameIds.forEach(e => {
            cancelAnimationFrame(e);
        });
        this.animationFrameIds.length = 0;
        // childrenAvailableCallback is implemented in each component
        // This would be the place where it is safe to setup the component
        // if it relies on children to setup properly.
        // One drawback is that this is going to happen after the DOMContentLoaded
        this.childrenAvailableCallback();
        if (this.mutationObserver) {
            this.mutationObserver.disconnect();
        }

    }
}
`



-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/webcomponents/issues/551#issuecomment-430925477

Received on Thursday, 18 October 2018 08:41:53 UTC