how to: include multiple files in a web page

When creating a website, it’s helpful to include multiple files on a page. You might want a header to display on every page, and don’t want to have to update every page whenever you change your it.

Here are a couple ways to include a resource on every page:

Method #1: PHP include

PHP is a server side programming language. This is, in my opinion, the best way to include other resources on a page.

You’ll need a server. You can use a localhost server (on your computer) or a web server. Because PHP is a server-side programming language, your browser probably won’t work.

First, create a file you want to include on your page, e.g. “heading.html”. Include the HTML for your header (or whatever you want to include) in this file.

Once you made an HTML file, create a PHP file (e.g. “index.php”). This file will be the main page that includes multiple resources. In your PHP file, use:

(replace “heading.html” with the link to the file you want to include, e.g. “/resources/heading.html”).

When you open this page on your server, it will include your file. When creating other pages, just include the same PHP code. Whenever you update your file, the page will be updated.

Method #2: Javascript

You can also include an element on every page using Javascript. Although this is not a clean as PHP, it will get the job done.

Create a javascript file (e.g. “heading.js“). In your javascript file write:

var toappend = "your html here";
document.getElementById("#holder").innerHTML = toappend;

On each page that you want your HTML to show up, include<script src="/heading.js" type="text/javascript"></script> in the head element, and <div id="holder"></div> where you want your HTML.

Advertisements