15

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

1
  • 1
    if you choose an jQuery answer as accepted change the title or at least add an tag to include that Commented May 11, 2022 at 8:19

8 Answers 8

16

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This is Vanilla JS, right?
@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.
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?
9

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>

3 Comments

What is #yourDiv? Is that the id of the desired location in the main html (aka index.html)?
It's the div wrapper to inject the HTML. E.G. <div id='yourDiv'>HTML will be injected here.</div>.
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.
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.

Comments

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).

Comments

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.

Comments

1
fetch("MyHTMLFile.html").then((response) => {
  response.text().then((text) => {
    targetHTMLElement.innerHTML = text;
  });
})

Comments

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

Comments

0

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

2 Comments

Why do you recommend that?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.