Skip to content

Commit

Permalink
feat: Allow for custom prerender injection selector
Browse files Browse the repository at this point in the history
  • Loading branch information
rschristian committed Dec 16, 2023
1 parent a82389f commit 204f633
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
1 change: 1 addition & 0 deletions demo/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export async function prerender() {
return {
html,
links,
selector: "#app",
head: {
lang: "en",
title: "Prerendered Preact App",
Expand Down
17 changes: 15 additions & 2 deletions src/prerender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,8 +329,21 @@ export function PrerenderPlugin({
}
}

// Inject pre-rendered HTML into the start of <body>:
htmlDoc.querySelector("body")?.insertAdjacentHTML("afterbegin", body);
if (result.selector) {
const el = htmlDoc.querySelector(result.selector);
if (!el)
throw new Error(
`Unable to detect prerender selector "${result.selector}" in input HTML template`,
);
el.insertAdjacentHTML("afterbegin", body);
} else {
const el = htmlDoc.querySelector("body");
if (!el)
throw new Error(
"No prerender selector was specified and <body> does not exist in input HTML template",
);
el.insertAdjacentHTML("afterbegin", body);
}

// Add generated HTML to compilation:
if (route.url === "/")
Expand Down

0 comments on commit 204f633

Please sign in to comment.