Share a header and footer across plain HTML pages without a framework
If you build small static sites in plain HTML, you hit this fast: the same header and footer are copied into every page, and one nav change means editing ten files. You can fix that without a framework. Here are three w
If you build small static sites in plain HTML, you hit this fast: the same header and footer are copied into every page, and one nav change means editing ten files.
You can fix that without a framework. Here are three ways, with the catch of each.
1. Load a partial with fetch
Put the shared markup in its own file, partials/header.html:
<header>
<a href="/">Home</a>
<a href="/about.html">About</a>
</header>
Then in each page:
<div id="site-header"></div>
<script type="module">
const res = await fetch('/partials/header.html');
if (!res.ok) throw new Error(`Header failed to load: ${res.status}`);
document.getElementById('site-header').innerHTML = await res.text();
</script>
The catches:
- It does not work from
file://. Browsers blockfetchon local files. Run a local server instead, for examplepython3 -m http.server 8000. - The header appears after the script runs, so you can get a small flash of missing content.
- Search engines and link previews may not see the header, because it is not in the raw HTML.
-
<script>tags inside the partial do not run when inserted withinnerHTML. Keep partials to plain markup.
Good for: small personal sites, prototypes, pages where the header is not important for SEO.
2. Include at build time
A ten-line Node script can paste the partial into each page before you deploy, so the final HTML is complete:
import { readFileSync, writeFileSync } from 'node:fs';
const header = readFileSync('partials/header.html', 'utf8');
const page = readFileSync('src/index.html', 'utf8');
writeFileSync('dist/index.html', page.replace('<!-- HEADER -->', header));
No flash, no extra request, and crawlers see everything. The cost is a build step before every deploy.
Good for: anything public where the header and footer matter.
3. Use a static site generator
If you have more than a handful of pages, tools like Eleventy or Astro give you layouts and includes out of the box. At that point, writing your own script is more work than learning one.
Which one?
- Two or three pages, local only: copy and paste is fine.
- A small site you will keep changing:
fetchfor speed, build-time include once SEO matters. - Many pages: a generator.
The two things that surprise people with fetch are the file:// block and the script tags that never run. Check those first if your partial does not show up.
AI disclosure: I drafted this with AI assistance and checked the code and the points above myself.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.