feat: async plugin rendering (#745)

An async render hook is added to plugins that enables injecting stylesheets and scripts based on the rendered HTML text.
This commit is contained in:
Tom
2023-06-06 12:36:04 +02:00
committed by GitHub
parent cd760b90d4
commit dd4e584a3e
6 changed files with 113 additions and 13 deletions
+8 -1
View File
@@ -1,5 +1,12 @@
import { FreshOptions } from "$fresh/server.ts";
import cssInjectPlugin from "./utils/css-inject-plugin.ts";
import jsInjectPlugin from "./utils/js-inject-plugin.ts";
import cssInjectPluginAsync from "./utils/css-inject-plugin-async.ts";
export default { plugins: [cssInjectPlugin, jsInjectPlugin] } as FreshOptions;
export default {
plugins: [
cssInjectPlugin,
jsInjectPlugin,
cssInjectPluginAsync,
],
} as FreshOptions;
@@ -0,0 +1,15 @@
import { Plugin } from "$fresh/server.ts";
let CSS_TO_INJECT = "h1 { text-decoration: underline; }";
export default {
name: "css-inject-async",
async renderAsync(ctx) {
await new Promise((res) => setTimeout(res, 50));
const res = await ctx.renderAsync();
if (res.requiresHydration) {
CSS_TO_INJECT += " h1 { font-style: italic; }";
}
return { styles: [{ cssText: CSS_TO_INJECT, id: "def" }] };
},
} as Plugin;