Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/plain-docs-start.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'preact-render-to-string': patch
---

A streamed full document now starts with `<!DOCTYPE html>` when nothing in it suspends too, so a page no longer switches to quirks mode once its data or lazy modules are cached on the server.
7 changes: 4 additions & 3 deletions src/lib/chunked.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ export async function renderToChunks(
const shell = renderToString(vnode, context, renderer);
if (onShellReady) onShellReady();

const prefix = shell.trimStart().startsWith('<html')
? '<!DOCTYPE html>'
: '';
// Wait for any suspended sub-trees if there are any
const len = renderer.suspended.length;
if (len > 0) {
Expand All @@ -47,17 +50,15 @@ export async function renderToChunks(
// and causes browsers to reject the content. Instead, we inject the deferred
// content before the closing tags, then emit them last.
const docSuffixIndex = getDocumentClosingTagsIndex(shell);
const hasHtmlTag = shell.trimStart().startsWith('<html');
const initialWrite =
docSuffixIndex !== -1 ? shell.slice(0, docSuffixIndex) : shell;
const prefix = hasHtmlTag ? '<!DOCTYPE html>' : '';
onWrite(prefix + initialWrite);
onWrite(createInitScript(nonce));
// We should keep checking all promises
await forkPromises(renderer);
if (docSuffixIndex !== -1) onWrite(shell.slice(docSuffixIndex));
} else {
onWrite(shell);
onWrite(prefix + shell);
}
} finally {
for (const pending of renderer.suspended)
Expand Down
16 changes: 16 additions & 0 deletions test/compat/render-chunked.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,22 @@ describe('renderToChunks', () => {
expect(html).to.match(/<template for="\d+"><p>it works<\/p>/);
expect(html).not.to.contain('undefined');
});

it('should prepend <!DOCTYPE html> when rendering a full document that does not suspend', async () => {
const result = [];
await renderToChunks(
<html>
<body>
<p>ready</p>
</body>
</html>,
{ onWrite: (s) => result.push(s) }
);

expect(result).to.deep.equal([
'<!DOCTYPE html><html><body><p>ready</p></body></html>'
]);
});
});

describe('createInitScript', () => {
Expand Down
Loading