Skip to content

Stream renderer(s) can close parent elements of suspended nodes early #415

Open
@rschristian

Description

@rschristian

Looking at some Remix/React-Router issues (CC @sbesh91, this isn't the only issue though) and came across this.

At the moment we don't split the document following any suspended children, only insert placeholder comments & continue on, which can cause issues when rendering a full page as react-router does.

Will need to look at other implementations yet, not familiar enough to say whether we should be splitting in all cases or if this is something we only need to deal with for body/html.


Take this input (more or less adopted from Remix/React-Router's template):

const stream = renderToReadableStream(
    <html lang="en">
        <head>
            <meta charSet="utf-8" />
        </head>
        <body>
            <div>
                <Suspense fallback="loading...">
                    <Suspender />
                </Suspense>
            </div>
        </body>
    </html>
);

This gives us stream chunks like this:

[
    "<html lang=\"en\"><head><meta charset=\"utf-8\"/></head><body><div><!--preact-island:70-->loading...<!--/preact-island:70--></div></body></html>",
    "<div hidden>",
    "<script>(function(){class e extends HTMLElement{connectedCallback(){var e=this;if(!e.isConnected)return;let t=this.getAttribute(\"data-target\");if(t){for(var r,a,i=document.createNodeIterator(document,128);i.nextNode();){let e=i.referenceNode;if(e.data==\"preact-island:\"+t?r=e:e.data==\"/preact-island:\"+t&&(a=e),r&&a)break}r&&a&&requestAnimationFrame((()=>{for(var t=a.previousSibling;t!=r&&t&&t!=r;)a.parentNode.removeChild(t),t=a.previousSibling;for(i=r;e.firstChild;)r=e.firstChild,e.removeChild(r),i.after(r),i=r;e.parentNode.removeChild(e)}))}}}customElements.define(\"preact-island\",e);}())</script>",
    "<preact-island hidden data-target=\"70\"><p>it works</p></preact-island>",
    "</div>"
]

The first chunk closes the html element (</html>) and so all the other chunks that come after will cause predicable errors when loaded in the browser:

Uncaught DOMException: CharacterData.after: Cannot have more than one Element child of a Document

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions