ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Javascript: Beautiful client-side includes

Updated on July 14, 2014

What is a client-side include?

To explain what a client-side include is, I want you to engage in a bit of imagination with me.

Imagine for a moment that you are a beginner, just getting started with website development. You've just set up your first website, and it looks pretty snazzy. The home page looks nice, but now you want to create some other pages. Perhaps a page where you'll post all that cheesy poetry you've been writing lately, and another page to plaster with photos of you new pet piranha.

To make moving between these pages nice and easy you put a neat little navigation bar at the top of the page, just like you've seen on so many other websites. You copy the markup and paste the navbar onto your other pages as well, but then a problem presents itself when you decide you want to add a fourth page.

The problem of course, is that every time you want to add a new page, you have to manually go through and edit every single page you've made so far, to update every one of their navbars to show a link to the new page. This is a very tedious and boring process, and becomes exponentially more daunting the more pages you add.

Server-side includes

This is the traditional solution to the problem. The markup for the navigation bar will be stored in a separate file, for example "navbar.html". Then on every page where you want the navbar to appear, you simply add a bit of script telling the server to put the navbar there.

It looks something like this:

<?php include 'navbar.html' ?>

Whenever the server receives a request to view your webpage, it will run all of the scripts and send the result to the client.

This method solves the problem quite beautifully. But wait, what if you can't use server-side scripting? Most professional web hosts have support for PHP, which is one of the most popular server-side scripting languages, but if you're using a webhost that doesn't support PHP, like neocities.org for example. Then you can't use this solution at all.

That's where Client-side includes come in handy.

Client-side includes

The advantage of using client-side includes is that unlike server-side includes, they should work with all webhosts. However, since the work is being done on the client-side, this means that the client-side includes might not work on all browsers. They will not work at all if javascript is disabled.

There's a few different methods for client-side includes, all of which use javascript, and I'm going to save the best for last, so scroll down if you're in a hurry.

The ugly way

The most common way I see client-side includes performed is also one of the most ugly and unpleasant things I have ever seen in my coding life. Let me explain.

The method involves wrapping the markup you want to include into one or more document.write statements, saving it in a .js file, and including the file like you would include a script.

Here's an example:

document.write("<div id='navbar'>");
document.write("<a href='/'>home</a> | ");
document.write("<a href='/poetry.html'>poetry</a> | ");
document.write("<a href='/piranha.html'>piranha</a>");
document.write("</div>");

You see what I mean about being ugly? It's definitely not beautiful at all.

But wait, there is a few tricks you can use to clean it up and make it look nicer. The first trick uses string concatenation. Here's what it looks like:

document.write("<div id='navbar'>"
+"<a href='/'>home</a> | "
+"<a href='/poetry.html'>poetry</a> | "
+"<a href='/piranha.html'>piranha</a>"
+"</div>");

Doing this allows us to break our string up over multiple lines, so we can wrap the whole thing up in one statement.

The second trick uses multiline strings. In javascript a string can be extended to the next line by ending that line with a backslash.

document.write("<div id='navbar'>\
<a href='/'>home</a> | \
<a href='/poetry.html'>poetry</a> | \
<a href='/piranha.html'>piranha</a> \
</div>");

This looks a lot better, but it's still very ugly.

After you have this separate file, you can include it on your page simply by placing the following markup where you want it to be included, replacing "navbar.js" with whatever you named your file.

<script src="navbar.js"></script>

The beautiful way

I've found that the best way to perform client-side includes is by using a technology called "ajax", which allows the client to make requests to the server.

For your convenience, I've created a neat little script for absolutely beautiful client-side includes, and the best part is, the script is tiny!

Here it is. I'll explain how to use it and how exactly it works further down.

function include(url){
  var xmlhttp;
  if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }else{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.open("GET",url,false);
  xmlhttp.send();
  var scriptTag = document.getElementsByTagName('script');
  scriptTag = scriptTag[scriptTag.length - 1];
  var parentTag = scriptTag.parentNode;
  parentTag.innerHTML += xmlhttp.responseText;
}

I've named the script file "include.js", but you can name the file something else if you wish. You can also change the name of the function inside the script if needed.

I said the best part of this script was that it was tiny, but in truth that's only the second best part. The real best part is that there's no special wrapping you need to worry about for the external file, nor do you need save it as a different format. It's just a regular html file.

<div id='navbar'>
<a href='/'>home</a> | 
<a href='/poetry.html'>poetry</a> | 
<a href='/piranha.html'>piranha</a> 
</div>

After you have your external file set up, there are only two steps to including it. First, you need to include the script in the head of your html file.

<script src="include.js"></script>

Next, you only need to place the following markup where you want the file to be included, replacing "path.html" with the path to your file.

<script>include("path.html")</script>

And you're done! As you can see, this method is much more beautiful than the more traditional client-side includes. It even rivals the server-side include in beauty and elegance!

I've set up an example site if you want to see my script in action. I have two includes on the example site, one for the navigation bar and one for the script in the code box. I also have links to the two files in the navbar.

How it works

So now you want to know how the script works? Well it's very simple. Let me break it down for you.

var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

This is the first part of the function. We're just declaring a variable called xmlhttp, and then assigning the ajax object to it. We need to do this in a different way depending on what browser the client is using.

xmlhttp.open("GET",url,false);
xmlhttp.send();

This next part is what initiates the ajax request. The last parameter on the "open" function call is very important. It's saying that the request will not be asynchronous, which means the script will not continue until the request is returned. This is important.

var scriptTag = document.getElementsByTagName('script');
scriptTag = scriptTag[scriptTag.length - 1];
var parentTag = scriptTag.parentNode;
parentTag.innerHTML += xmlhttp.responseText;

This is the final part of the function. The first three lines are to ensure that the markup is inserted into the correct parent object, and the fourth line is the one that actually adds the markup to the page.

Thank you for reading!

I hope this hub has been helpful to you. Please feel free to use the script I've shown you without any reservations, and if you have any questions then please feel free to leave a comment!

© 2014 Dreadwing93

Comments

    0 of 8192 characters used
    Post Comment

    • gmmurgirl profile image

      G Maria 3 years ago from Philippines

      Useful tips for web developers even for beginners. Thanks!

    working