client side includes
the other day my cubicle-neighbor got a phone call, and i was asked to go over and help someone with a web page they’re making. this is what happens when you’re an intern: “go do this that nobody else has time to do nor even wants to do”. anyways, it turned out to be a rather interesting problem:
the servers at our organization don’t support server-side-includes, allegedly because the “.shtml” part of a url that is requred for pages that use them is to foreign and not user-friendly for our users. i personally don’t like the “.shtml” part of urls because it feels like a bad word :P. but regardless, it is quite annoying and error-prone when you’re making a static html site, to have to go through every single page and update the navigation menu, or some other part that’s on every page, in each and every one whenever it changes. what to do, eh? you could use some other server-side technology like ASP or PHP, but not if you’re not a programmer and the people who will be maintaining the site aren’t programmers either.
something i’ve never even thought of before, nor seen done before, is the idea of including something, on the client side. if it’s just html, why not? so i looked up a javascript library i’ve heard a lot of hype about, called jquery. i’ve seen jquery, mostly on job listings where it’s being asked for as either a required thing to know, or a major bonus. this is because it’s a pretty sweet library, rightly known as “the write less, do more, javascript library”.
this code:
$(document).ready(function(){
$("#nav").load("nav.html");
});
will go and fetch the contents of “nav.html” (presumably the HTML code for your site navigation menu) from your server, and place that between whatever tags have the ID attribute “nav”:
<div id="nav"></div>
once the page loads and the DOM is ready to manipulate with javascript, the HTML for the navigation is loaded. it works in any commonly-used browser from IE6+, Firefox 2+, Safari 3+, Chrome, and of course Opera 9+.
a couple of years ago this wasn’t such a trivial thing to do. you would have had to create an XmlHTTPRequest object by hand, using different methods depending on what browser is being used, write a callback function to get into the DOM and manipulate things and insert stuff. here all that is handled for you, and i think i’m in love with jquery, because it’s so dang sexy.