Search code examples
javascriptweb-applicationsmodal-dialogweb-componentshadow-dom

Is shadow DOM on <body> element a bad idea?


Use case: A modal dialog box that, when invoked, needs to take up 100% H/W and function of all other body ancestor DOM elements. There is only one of these per page/web-app, which can hopefully be enforced when Javascript Modules arrive.

I could easily request the web-author provide something like a <DIV></DIV> to my web-component, a la mode de Google Maps, but is there anything intrinsically bad with attaching a Shadow DOM to document.body? It's certainly an error free option on Chrome.

A related problem is can I replace an element's shadow DOM post render? I know Shadow DOM 1.0 only permits 1 shadow DOM per element but my use case is, at run-time, I need to heuristically assemble the appropriate Template to satisfy the given temporal environment/ambiance. One way I thought of was to attach an empty Shadow DOM at load-time thereby preventing any <SLOT> contenders from rendering and then, when I know what UI needs to be in place, swap/clone/replace the place-holder Shadow DOM with the full-blown ridgy didge template content.

So: - 1) Is BODY as a HOST ok? 2) What is best-practice for replacing Shadow DOM?


Solution

  • 1) Is BODY as a HOST ok?

    Yes

    2) What is best-practice for replacing Shadow DOM?

    Use either:

    body.shadowRoot.innerHTML = [new template innerHTML] 
    

    or:

    body.shadowRoot.replaceChild( newNodes, oldNode )
    

    or:

    body.shadowRoot.innerHTML = ''
    body.shadowRoot.appendChild( newNodes )
    

    With template.content you get directly the already parsed DocumentFragment so it could be faster in some situations, while with template.innerHTML you can take profit of template literals, and then include the values of some variables.