1. Technology

How To Include HTML in Many Documents Using JavaScript

By

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 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
  2. Since HTML is not JavaScript, you need to add the JS code document.write to every line.
    document.write("Copyright Jennifer Kyrnin 1992");
  3. Open the Web page where you want the include file to display.
  4. Find the location in the HTML where the include file should display, and place the following code there:
    <script type="text/javascript" src="includes/copyright.js">  </script>
  5. Change the path and file name to reflect your include file location.
  6. Add that same code to every page you want your copyright information on.
  7. 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 an JavaScript include file. Anything that can go in an standard HTML file can go in an JavaScript include file.
  3. You can put JavaScript includes anywhere in your HTML document, including the head.
  4. The Web page document won't show the HTML that is included, only the call to the JavaScript script.
  1. About.com
  2. Technology
  3. Web Design / HTML
  4. Javascript and Ajax
  5. How to Include HTML in Many Documents Using JavaScript

©2014 About.com. All rights reserved.