A Cool Site for learning different

Sunday, August 21, 2011

JavaScript Includes

JavaScript Includes


If you know what server side includes are then you will also know how useful they can be 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 web 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:


<script src="menu.js" type="text/javascript">

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

A JavaScript function called loadmenu() which is in menu.js is called from each of the pages. 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 single quotes. You can include just about any html code with this so give it a try and enjoy having less work maintaining your website.