Baby steps: starting with jQuery - part 2

Implementing jQuery

Now that I've decided to use jQuery for my little task of breaking out of a framing site and telling the visitor why without an annoying alert, the first job is to make jQuery available for use. That's simple, but you still have choices - each with pros and cons. One way or another, the library itself needs to be linked from the <head> of your HTML document.

Hosted or local?

The obvious way has always been to just download the library, and stick it on your server. It seems the "polite" thing to do after all. The advantage is that you're not dependent on an external server, and what you have is stable. The disadvantage is that your server may not be the fastest ever (especially on shared hosting), and you have to watch for upgrades yourself.

The alternative is to use a hosted solution. One is provided by Google AJAX Libraries API, a.k.a. Google's CDN, which hosts a growing list of the most popular, open source JavaScript libraries, including jQuery. There are two ways to use it: you can either directly link to it, like this:

  1. <script type=”text/javascript” src=””></script>
Google will always have the latest version available, but note the version number in the URL. That's fine if you don't want to be surprised by version updates, but a pain if you want to take advantage of Google keeping up with the latest version for you, so Google provide an API to just pull the latest version: first you load the API, and at the start of your own script, you tell the API to load the latest jQuery, like so:

  1. <script type="text/javascript" src=""></script>
  2. <script type="text/javascript">
  3. // Load jQuery
  4. google.load("jquery", "1");
  6. // ... your script here
  7. </script>
So with Google you get the best of both worlds: either a stable version with no upgrade surprises, or always the latest if you prefer that.

An alternative to Google is to get it from the jQuery site itself. Many sites (including very big ones) have always done this, putting a huge load on a site that's obviously not as big as Google. The solution was to move all the jQuery code to Amazon S3: it's still on the same main domain, but the "code" subdomain is actually on Amazon's S3 servers. To use this hosted solution, you link directly to it:

  1. <script type=”text/javascript” src=””></script>
As the URL suggests: you always get the latest that way.

So what is best? It depends. It depends on whether you prefer a stable version or always the latest, on what kind of server you have available (and how fast it is), and where both your server and the jQuery hosting server are located with respect to your visitors. So YMMV. I've tried both hosted solutions: I found the Amazon-hosted jQuery site fast and reliable (yes, S3 has been know to go down, too — but so may your own server!) and I found Google's servers invariably slow, but that may be very different for you and, more importantly, for your visitors. The important thing is: you have options, and you should try them out to find what's optimal for you and your visitors.

Let's go local

This time, I've decided to just have the main script local (that is, on my own server). I'm actually using a few servers (for now, but that will probably change) each with a number of sites, and I'd like an implementation that is consistent across all. The first step is to choose a location for the source which has to be shared by sites on different virtual hosts. My general solution for shared code is to stick it completely outside the web server docroot in a directory /usr/local/src (I created src, and may have subdirectories to organize things there as well). I downloaded both the human-readable version (to learn from) and the "minimal" version (all whitespace removed). Of course, the version number is in those files, so to abstract it, I also created a symlink to the minimal version; so this is what I end up with:

  1. % ln -s jquery-1.3.2.min.js jquery.js
  2. % ls -la
  3. total 186
  4. drwxr-xr-x 2 javawoma vuser 512 Apr 14 12:30 .
  5. drwx--x--x 26 javawoma vuser 1024 Apr 14 12:21 ..
  6. -rw-r--r-- 1 javawoma vuser 120763 Apr 13 11:29 jquery-1.3.2.js
  7. -rw-r--r-- 1 javawoma vuser 57254 Apr 13 11:27 jquery-1.3.2.min.js
  8. lrwxr-xr-x 1 javawoma vuser 19 Apr 14 12:30 jquery.js -> jquery-1.3.2.min.js

The next step is to make that version-abstracted code available to my websites. I made an interesting mistake there: for a number of applications, to make a shared file available to various websites I simply symlink files from a web-visible directory to a file in the /usr/local/src directory tree. That works beautifully if it's PHP including those files: it works because PHP uses the file system for including files. Unfortunately, that didn't work in this case, since the file is needed by the browser instead of by PHP. Never mind that it's symlinked, I got an "Access Denied"! I should have known better, of course, but it can be hard to get out of a habit!

Apache to the rescue with the Alias directive. Unfortunately, this works only in the main httpd.conf or at virtual host level, but not in a .htaccess file, so if you have several sites on shared hosting, the hosted jQuery becomes a lit more attractive, as it saves you from storing the same file several times, once for each site. Luckily, my servers are all VPS systems, so I can use Alias in the main httpd.conf, or an included file for a specific virtual host.

One thing I just keep forgetting: you cannot use Alias to "add" files to an existing directory. I generally have a "js" or "scripts" directory for what little bits and pieces of JavaScript I use but if you use Alias to map the actual source location into a "js" directory, it will create a new virtual "js" directory, and make the existing one invisible! Thus my first attempts miserably failed. Finally, I decided to use a virtual "jq" directory next to the existing (real) "js" one, like this:

  1. # map /usr/home/javawoma/usr/local/src into URL path 'jq' to make jquery script visible
  2. Alias /jq /usr/home/javawoma/usr/local/src
(Yes, that source path is a little funny, but that's because the VPS on this particular server is a bit weirdly set up.)

First lines of jQuery

Of course, to figure out whether I had a functional jQuery setup (which I didn't at first!) I needed a little code to test it. First of all, a little HTML to use as a testing framework; it needs to include the (aliased) jQuery library, as well as my own script which uses jQuery and which I'll call justsayno.js:

the HTML:
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  3. <html>
  4. <head>
  5. <title>jQuery test</title>
  6. <script type="text/javascript" src="jq/jquery.js"></script>
  7. <script type="text/javascript" src="js/justsayno.js"></script>
  8. </head>
  9. <body>
  10. <h1>Just Say No!</h1>
  11. <p>This is the normal content of this page. We'll use it to develop a jQuery frame alerter and redirector.</p>
  13. </body>
  14. </html>

For my own script, I needed something very basic to show, first of all, that the script itself is active, and then a little jQuery to show the library is available. Where to start? When starting with a new language, I normally get up to speed fastest when I can see some practical code samples (using jQuery effectively is using a new language) so I did some browsing, and soon found Rick Strahl's An introduction to jQuery - Part 1: The Client Side which provides an excellent introduction in a compact and well-organized article - just what I needed!

After I'd digested most of that, I started with an alert (to show my script was loaded), and then a reversed test to see if we're framed (testing if we're framed is of course useless as long as we're not, so the test is negative while developing my script). Within that condition we're actually going to do our stuff, and this is where the jQuery gets in: we wait for the document to be ready, and once it is, add a class and a style to the body element. This was my first working code:

the script:
  1. alert('this is "justsayno.js"');
  2. // test if we are within a frame
  3. if (top === self) { // use the positive to test, negative later!
  4. alert('we are NOT inside a frame');
  5. // do our jQuery stuff here
  7. // first, wait for the document (DOM!) to be ready, then apply changes to the body
  8. $(document).ready( function() { // object, not in quotes
  9. alert('the DOM is ready!');
  10. $("body") // select body (selector, so in quotes)
  11. .addClass("ready") // applies to body which is selected
  12. .css("background-color","lightgrey");
  13. alert('and now the background should be grey');
  14. });
  16. // now, the background color of the body should be light grey, and it should have a class
  17. // BUT this bit of code *doesn't* wait till the DOM is ready, so this alert actually appears
  18. // before the DOM is ready!!
  19. alert('we\'re going to set a grey background now!');
  20. }

It works! And looking at the HTML with Firebug once the script has finished shows that the body element has acquired two new attributes:

  1. <body class="ready" style="background-color: lightgrey;">

An interesting bit in this little script is that the last alert in the script will come up before the "and now the background should be grey" one: that is because the last alert is outside the ready() function which waits for the document to be ready: since it doesn't wait, it comes up right away, while what's inside the $(document).ready() function will wait till the document (or the DOM) is indeed ready (and rendered) before doing its stuff. That's an interesting little illustration of the asynchonicity of this JavaScript: logical once you grasp it, but counter-intuitive until you do.

I was quite excited once I got to this point: my first working jQuery script (that I didn't copy from somewhere)! In the next installment, I'll develop this further in the direction of what I really want to do with it. We'll have some interesting adventures ahead - stay tuned!

Other parts in this mini-series:

0 Responses to Baby steps: starting with jQuery - part 2

  1. There are currently no comments.

Leave a Reply

Some HTML allowed (like a, em, strong, pre). If you want to embed a code fragment, its syntax will be highlighted if you surround it in pseudo-tags like this:
[geshi lang="php"]echo 'highlighted code!';[/geshi] (instead of using pre); specify language in the lang attribute. Do not enclose your code in tags like <?php … ?> as that will make it disappear.