feat: elide __FRSH_PROPS for no data or params (#33)

Minor size improvement.
This commit is contained in:
Luca Casonato
2021-06-12 00:23:59 +02:00
committed by GitHub
parent 3ad4a84b51
commit 18feea9c45
4 changed files with 25 additions and 15 deletions
-1
View File
@@ -21,4 +21,3 @@ export {
useRef,
useState,
} from "https://x.lcas.dev/preact@10.5.12/hooks.js";
import "https://x.lcas.dev/preact@10.5.12/debug.js";
+2 -2
View File
@@ -122,9 +122,9 @@ import Page from "${page.url}";
import { h, render, DATA_CONTEXT } from "${runtime.href}";
addEventListener("DOMContentLoaded", () => {
const { params, data } = JSON.parse(document.getElementById("__FRSH_PROPS").textContent);
const { params, data } = JSON.parse(document.getElementById("__FRSH_PROPS")?.textContent ?? "{}");
try {
render(h(DATA_CONTEXT.Provider, { value: new Map(data) }, h(Page, { params })), document.getElementById("__FRSH"));
render(h(DATA_CONTEXT.Provider, { value: new Map(data ?? []) }, h(Page, { params: params ?? {} })), document.getElementById("__FRSH"));
} catch(err) {
if (err instanceof Promise) {
console.error("Render tried to suspend without a suspense boundary.");
+22 -8
View File
@@ -39,11 +39,25 @@ export async function render(opts: RenderOptions): Promise<string> {
const bodyHtml = await render();
let templateProps: {
params?: Record<string, string>;
data?: [string, unknown][];
} | undefined = { params: opts.params, data: [...dataCache.entries()] };
if (Object.entries(templateProps.params!).length === 0) {
delete templateProps.params;
}
if (templateProps.data!.length === 0) {
delete templateProps.data;
}
if (Object.entries(templateProps).length === 0) {
templateProps = undefined;
}
const html = template({
bodyHtml,
imports: opts.imports,
preloads: opts.preloads,
props: { params: opts.params, data: [...dataCache.entries()] },
props: templateProps,
});
return html;
@@ -57,8 +71,6 @@ export interface TemplateOptions {
}
export function template(opts: TemplateOptions): string {
const props = JSON.stringify(opts.props);
const page = (
<html>
<head>
@@ -67,11 +79,13 @@ export function template(opts: TemplateOptions): string {
</head>
<body>
<div dangerouslySetInnerHTML={{ __html: opts.bodyHtml }} id="__FRSH" />
<script
id="__FRSH_PROPS"
type="application/json"
dangerouslySetInnerHTML={{ __html: props }}
/>
{opts.props !== undefined
? <script
id="__FRSH_PROPS"
type="application/json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(opts.props) }}
/>
: null}
</body>
</html>
);
+1 -4
View File
@@ -17,10 +17,7 @@ Deno.test("/ page prerender", async () => {
body,
`<script id="__FRSH_PROPS" type="application/json">`,
);
assertStringIncludes(
body,
`"params":{}`,
);
assert(!body.includes(`"params"`));
assertStringIncludes(
body,
`"data":[["home","Hello!"]]`,