13

I have some html pages with the same footer. With JavaScript and only JavaScript could I import another html page inside it?

walves
  • 2,026
  • 6
  • 28
  • 46

8 Answers8

13

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;
}
ajax.open("GET", "footer.htm");
ajax.send();

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.

gilly3
  • 87,962
  • 25
  • 144
  • 176
  • This is Vanilla JS, right? – carloswm85 Jul 02 '22 at 15:24
  • 2
    @carloswm85 - yes, but it's out of date. Since 2011 it's more common to use `fetch` instead of `XMLHttpRequest`. I'll give my answer a 2022 update. – gilly3 Jul 13 '22 at 18:02
  • I've also seen some using the js module system to either import with "import myHtml from htmlPath" or an import syntax like "await import(htmlPath)" but I'm not sure when this would be preferred over fetch, or the differences between these 2 "import" strategies? – David Mays Aug 25 '23 at 14:05
10

As above, one method is to use jQuery load. I happened to be doing the exact same thing now, so will post a quick example.

Using jQuery:

$("#yourDiv").load('readHtmlFromHere.html #readMe');

And your readHtmlFromHere.html page would consist of:

<div><div id="readMe"><p>I'm some text</p></div></div>
Ricky
  • 7,785
  • 2
  • 34
  • 46
  • 2
    What is #yourDiv? Is that the id of the desired location in the main html (aka index.html)? – Jacobo Koenig Oct 31 '16 at 20:20
  • 1
    It's the `div` wrapper to inject the HTML. E.G. `
    HTML will be injected here.
    `.
    – Ricky Nov 01 '16 at 09:24
  • How about doing it in pure, vanilla JS (I mean, without the use of jQuery or any other libraries)? I actually wanted to "import" an html template file to a variable first so I could manipulate its content before appending it to an html element. – Fabricio Dec 14 '21 at 18:00
3

You can use ajax to return a whole HTML page. If you wanted to replace the whole page you could replace the body tag and all it's children currently on the page with the body tag returned from the ajax call.

If you wanted to just replace a section you'd have to write a server-side script to create that section, then use ajax as above but just replace an element rather than the whole page.

Alex
  • 7,320
  • 1
  • 18
  • 31
2

Along with what @Alex mentioned, jQuery has a method .load() that you can use to fetch a specific portion of a page (See Loading Page Fragments heading on that page). You specify the URL you want to retrieve along with a selector (so if you wanted only a specific <DIV>'s contents for instance).

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
1

Following this answer example (one of the answer in this question), I made this little reusable function:

/**
 * Render the array of html files, to the
 * selected container.
 * @param {*} pages - array of html file names
 * @param {*} container - HTML element name
 */
function render(pages, container) {
    const template = document.createElement("template");
    var ajax = new XMLHttpRequest();

    pages.forEach(element => {
        // this is the route where the files are stored
        ajax.open("GET", `./view/shared/${element}.html`, false);
        ajax.send();
        template.innerHTML += ajax.responseText;
    });

    document.querySelector(container).append(template.content);
}

export { render };

Which you can use in your index.js file, like so:

import { render } from "./tools/render.js";

var headerContent = ["siteName", "navbar"];

render(headerContent, "header");

This is rendering the html files siteName.html and navbar.html, into the <header> tag in the root index.html file of the site.

NOTE. This function works on localhost, but for whatever reason (which I still have to fix; I'll let you know when I do) it does not work correctly when working on GitHub Pages.

carloswm85
  • 1,396
  • 13
  • 23
0

You could do a server side include, depending on your webserver. but the quickest way would probably be to create a JavaScript file that uses document.write or similar to output the html syntax. and then just include the created JavaScipt file the normal way. more info at: http://webdesign.about.com/od/ssi/a/aa052002a.htm

Stephan
  • 1,505
  • 1
  • 11
  • 19
0

You definitely could, but if all you're doing is templating I recommend you do this on the server.

Andrew Noyes
  • 5,248
  • 1
  • 18
  • 14
  • Why do you recommend that? – carloswm85 Jul 02 '22 at 17:19
  • @carloswm85 I assume performance would be faster, since page will be rendered before delivered to client, and less likely that client will see things flashing as the page gets rendered locally. – johny why Dec 15 '22 at 18:34
0
fetch("MyHTMLFile.html").then((response) => {
  response.text().then((text) => {
    targetHTMLElement.innerHTML = text;
  });
})
Doron Saar
  • 446
  • 5
  • 7