3 Ways to Include Files on Your Website
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:
path/to/file.html with the path to your file.
If the file is in a different folder:
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
5include($_SERVER['DOCUMENT_ROOT'] . '/path/to/file.php');
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.
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
9var thisScript = document.currentScript;
Those are some of the easiest ways to include the same files on multiple pages. Let me know if there are any I missed!