This site uses third-party cookies, learn more or accept
dark light

3 Ways to Include Files on Your Website

Written by Max Pelic on
Update: the Jelly URL link shortener is live, be one of the first people to check it out!
For a limited time, get an exclusive discount by using the coupon code WEBSITE5OFF when you sign up for a free trial.

In this article I'll go over three different ways to include files on your website, ranked from best to worst.

It's helpful to include some files on multiple pages of your website to make it easy to keep all your pages up to date. Commonly people include a header file, footer file, and some other files.

Method 1: Server Side Include (SSI)

If your website is hosted using Apache, and has Server Side Includes turned on, you can use this method to include files on your page.

To use this method, you need use the .shtml extension on the files that will contain other files.

If the file is in the same folder:

1<!--#include file="path/to/file.html"-->

Replace path/to/file.html with the path to your file.

If the file is in a different folder:

1<!--#include virtual="/path/to/file.html"-->

In this example, replace /path/to/file.html with the absolute path to your file.

Method 2: PHP Includes

I ranked this option lower than "SSI" because you have to use PHP. If you're already using PHP on your site, this is the way to go.

1//include a file using the relative path

4//include a file using the absolute path
include($_SERVER['DOCUMENT_ROOT'] . '/path/to/file.php');

Method 3: Javascript

I really dislike this method, because it requires another resource to load before you can view the page. However, if you need to include files on a static site and can't compile your files beforehand, this is the only option.

Start by creating a Javascript file (in the example, we'll call it /js/heading.js).

In your Javascript file, enter your html and the code to add it to the site:

1var html = "HTML to include on your page";

3/*insert the html in a new element
4you could use a different parent tag, but I chose the span tag*/

5var newElement = document.createElement('span');
6newElement.innerHTML = html;
8//add the html to the document before the script element
var thisScript = document.currentScript;
10thisScript.parentElement.insertBefore(newElement, thisScript);

In your html file, add a link to your javascript file where you want to include the html:

1<script src="/js/heading.js"></script>

Those are some of the easiest ways to include the same files on multiple pages. Let me know if there are any I missed!

Share this article:

Next Article: Create a PHP Blog - no Database Needed!