Skip to content

JS-based HTML Include

Sometimes when I was drafting a website using pure HTML+CSS, I thought it would be nice to have some kind of includes for repetitive content such as the site header, etc. Sometimes I ended up using PHP, but today I just realised I could use JS instead.

window.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('[data-inject]').forEach((el) => {
    fetch(el.getAttribute('data-inject')).then((r) => r.text()).then((r) => {
      el.innerHTML = r;
    })
  })
})

This will just look for any element with attribute data-inject="file.html" and will inject the content of that file to the innerHTML. Neat, eh?

A word of warning

This technique requires a web server. It will not work with the file:// protocol. I mostly just use the WebStorm built-in server or the PHP development server.