Preloading Custom HTML with SvelteKit Hooks

December 11, 2024

Preloading Custom HTML with SvelteKit Hooks

Table of Contents

The Problem

Normally in Svelte, when you want to render dynamic content on the page, you would do so inside +page.svelte files. This doesn’t work if you want to add a custom class or other attributes to the <html> or <body> tags during the SSR process.

The Solution

Instead, you can create a custom hook to replace a specific string in your app.html file.

A SvelteKit hooks’ resolve method takes a transformPageChunk function that allows you to modify the HTML before it is sent to the client. This is useful for replacing strings in the HTML with dynamic values, that otherwise wouldn’t be accessible to modify in the Svelte code.