How to Include HTML in Many Documents Using JavaScript

If you want the same content copied over multiple pages of your site, with HTML you'll need to manually copy and paste that content. But with JavaScript, you can include snippets of code without any server scripts.

Difficulty: Average

Time Required: 15 minutes

Here's How:

  1. Write the HTML you want to be repeated and save it to a separate file.
    I like to save my include files into a separate directory, usually "includes". I would save my copyright information in an include file like this:
    includes/copyright.js
  1. Since HTML is not JavaScript, you need to add the JS code document.write to every line.
    document.write("Copyright Jennifer Kyrnin 1992");
  2. Open the Web page where you want the include file to display.
  3. Find the location in the HTML where the include file should display, and place the following code there:
     
  4. Change the path and file name to reflect your include file location.
  5. Add that same code to every page you want your copyright information on.
  6. When the copyright information changes, edit the copyright.js file. Once you've uploaded it, it will change on every page of your site.

Tips:

  1. Don't forget the document.write on every line of your HTML in the js file. Otherwise, it won't work.
  2. You can include HTML or text in a JavaScript include file. Anything that can go in a standard HTML file can go in a JavaScript include file.
  3. You can put JavaScript includes anywhere in your HTML document, including the head.​
  1. The Web page document won't show the HTML that is included, only the call to the JavaScript script.