How do I include another file inside a HTML file?
On a website the HTML pages often contain common elements. Because these elements are used more then
once, it would be very useful if you could store them separately, and glue them together with the
rest of the page when the page is requested. Programming languages often have instructions to include
common files, but HTML doesn't provide a function to import the contents of another file. But there
are solutions to this problem.
Server Side Includes
The first one is to use Server Side Includes (SSI). With SSI you can put instructions in the HTML
files that are executed by the http server. When executed, the server replaces the text of the SSI
instruction with the resulting text. The exact syntax of SSI instructions might differ for each
webserver, but it looks something like this:
|
<!--#include file="footer.html" -->
|
Because the server must do some extra processing on a file that contains SSI, it will result in
a slight loss in performance. For that reason most servers will not parse every file unless
configured to do so. So the server must be instructed to scan a file for SSI. Usually this is done by
changing the extension of the HTML file to .shtml or .sht. Read the documentation of your
webserver for exact instructions how to activate SSI, and the syntax you must use.
Including other files is just one action that can be triggered by SSI. Other instructions can
execute a program on the server, or retrieve values of the system or the webserver, like the name
of the webserver, dates when files are changed, file sizes etc.
JavaScript
A second solution involves JavaScript. With the latest browsers you can include scripts from
external files. The contents must be JavaScript instructions, but by including the HTML you need
inside a JavaScript function, you can overcome this restriction.
First create a javascript file, for example footer.js
(the extension must be .js).
In this file you store the HTML you want to reuse:
|
var cText = ''
cText += 'put the html you want to include in lines'
cText += 'like these.'
cText += '<a href="copyright.html>Copyright notice</a>'
document.write(cText)
|
Now you must add an instruction to read this file in your html files that use the file. You must put
this tag at the position where you want the text to be used:
|
<script language="javascript" src="footer.js">
|
Usage
Which solution should you use? The advantage of using SSI instead of JavaScript, is that SSI is
handled on the webserver. This means that it will work with every browser. The other solution will
only work if the browser supports JavaScript.
Back to the FAQ main page
Copyright © 1996 - 2000 Rob Schlüter,
schluter@knoware.nl
(last updated 1999/03/01)