Learn Programming

JavaScript Includes

Introduction

If you know what server side includes are then you will also know how useful they are and how much easier they make it to make changes to all the pages on your website at once. The problem with SSI is that not all hosts, especially free ones, support it. There is a way to include the files on the client's side using JavaScript and it is called JavaScript Includes.

Including a menu

The first thing we must do is create a few pages of a website. Create page1.html, page2.html, page3.html in the same directory and then type the following in them changing the headings to the page number as you do it:

<html>
 
<h1>Page1</h1>
 
<script src="menu.js" type="text/javascript">
loadmenu();
</script>
 
</html>

Now create a file called menu.js. Type the following in the new file:

function loadmenu()
{
document.write('<a href="page1.html">page1</a><br>');
document.write('<a href="page2.html">page2</a><br>');
document.write('<a href="page3.html">page3</a><br>');
)

How it works

From the pages you are calling a JavaScript function called loadmenu() which is in menu.js. The function writes the menu when it is called and since it is called from the same file, menu.js, in all 3 pages it displays the same menu for them. You can add more menu items simply by copying one of the document.write lines and changing the code between the apostrophes. You can include just about any html code with this so give it a try and enjoy having less work maintaining your websites.