How can I reuse HTML code across several HTML files

There are three places you can do this:

When you build the site, before/during deployment.

This is a step where you take the source code you’ve written (along with any data you want to pull from, for example, a database) and convert it to code (and content) suitable to be copied to your server and then sent to browsers.

You can use any programming language you like for this. Generally you would use a template library and inject the content in it from a series of source files.

There are lots of static site generators which are designed to do this. Jamstack has a longer list (albeit with less explanation).

On the server

You’ve rejected PHP, but it or another server side language are common choices for this sort of problem, be it with a simple set of includes, something slightly smarter with templates or a full on big CMS.

On the client

Pulling content over HTTP with client-side JS and then injecting it into the page is a fairly simple option, but the least friendly to search engines and most likely to break due to client issues (like network timeouts for individual files or ad-blockers).

More complex systems would use tools like React but the best of those are backed by server-side rendering (e.g. via Next.js) or build-time generated static files (e.g. via Gatsby). That is to say you use option 1 or option 2 and then add client-side to enhance the UX and performance.

Leave a Comment