Rocket Template Loader Pro

Rocket is currently in alpha – available in the Datastar Pro repo.

This example demonstrates the same Rocket template-loading pattern used by this site. It is implemented in Go + templ here, but the pattern is framework-agnostic.

 1templ LoadRocketTemplates(templatePaths ...string) {
 2    {{
 3        templateURLs := make([]string, len(templatePaths))
 4        for i, templatePath := range templatePaths {
 5            templateURLs[i] = StaticPathF("rocket/%s.html", templatePath)
 6        }
 7    }}
 8    <script>
 9        Promise.all({{ templateURLs }}.map(async (url) => {
10            const res = await fetch(url)
11            const html = await res.text()
12            document.documentElement.insertAdjacentHTML("beforeend", html)
13        }))
14    </script>
15}
16
17...
18
19@LoadRocketTemplates("copy-button", "rocket-counter")

This turns into a script that looks like this in the rendered HTML:

1<script>
2    Promise.all(["/static/rocket/copy-button.html", "/static/rocket/rocket-counter.html"].map(async (url) => {
3        const res = await fetch(url)
4        const html = await res.text()
5        document.documentElement.insertAdjacentHTML("beforeend", html)
6    }))
7</script>

Why This Approach #

The template files are static assets, so they can be cached by normal HTTP caching. That keeps component definitions reusable without inlining large <template data-rocket:*> blocks in every page.

Open your browser's dev tools and inspect the page source. You should see that the templates are cached and only loaded once, even though multiple pages use the same Rocket components. It also means you can use speculative prefetching or other optimizations on the template files if desired.