Is it possible to import HTML using JavaScript?

Here’s how you could use just javascript to add a footer to your page.

2022 code, using fetch and insertAdjacentHTML:

async function addFooter() {
    const resp = await fetch("footer.htm");
    const html = await resp.text();
    document.body.insertAdjacentHTML("beforeend", html);

Original 2011 code, using XMLHttpRequest and innerHTML:

var ajax = new XMLHttpRequest();
ajax.addEventListener("load", function () {
    document.body.innerHTML += ajax.responseText;
}"GET", "footer.htm");

The 2011 code will still work in all browsers today, but fetch is more intuitive, and allows you to avoid coding an event handler callback. insertAdjacentHTML is also available for all browsers, so you could use that or innerHTML with either example. Only fetch is new, and won’t work in IE without a polyfill.

Leave a Comment