ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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 

      4 years ago from Philippines

      Useful tips for web developers even for beginners. Thanks!

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)