No Mod Required

Archive for the 'Code I Like' Category

Code I Like - Link Prefetching

I was reading John Resig's Browser Page Load Performance post earlier today and followed up from there on the concept of Link prefetching. Currently supported by Firefox 2+, Link prefetching is a browser based mechanism for fetching "future" content. Considering I wrote (and ultimately scrapped*) similar functionality for my gallery pages, I was obviously intrigued.

In its basic version it looks like this:

<link rel="prefetch" href="/images/big.jpeg">

With the href being the target content and the rel attribute triggering the prefetching mechanism. Pretty simple. I've already implemented it here on my gallery pages.

One thing I would like to see, and this is hinted at on the above linked Mozilla FAQ page, is prefetching performed automatically on anchor (<a>) tags with rel attribute set appropriately. In my mind that would be any anchor with a rel attribute of next, but the prefetch value would be fine as well. Personally, if that were supported I wouldn't have any (or very little) work to do to take advantage of this feature and in a general sense it would build on what people are already doing using prev, next and toc rel attributes on gallery links.

*it was scrapped because I hated the idea of forcing bandwidth usage on people with metered accounts. Since this is a browser based mechanism, it should be relatively painless for people in that situation to control whether or not content is prefetched.

Code I Like: Using Apache's .htaccess and mod_rewrite to Redirect All Traffic to "www"

I know I was talking about HTML/CSS and JavaScript when I started this series, but I never said anything about being exclusive to the presentation layer :)

And heck, there's always room for Apache when I'm talking about technology…

Anyway, a common practice in SEO circles is to 301 (301 the http status code for "moved permanently") redirect all traffic to one version of a domain in order to maximize the power of links that flow into the site. Why? Well, search engines see http://www.example.com/link1.html and http://example.com/link1.html as two separate files, so it's beneficial to flow links into one or the other. That way if there are two links to http://www and two links to http:// they will get together and make four. Four is more than two and in this case more is definitely better.

In the case of drunkenfist.com I redirect all traffic to www.drunkenfist.com. Here's how I do it. I place something similar to the following code in my .htaccess file (where example.com is my domain name):

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

This is common enough code, but I'll go through it line by line so that you actually know how it works. A lot of time when people post code like this they gloss over the specifics and just let the Apache magic happen. Not me. Especially since writing this stuff forces me to understand each subject just that much more.

Here we go.

Options +FollowSymLinks

This line tells Apache to follow symbolic links. For those of you unfamiliar with unix-like file systems, links in this sense aren't the HTML links you're familiar with, but are instead file system links similar to, but more powerful than, Windows shortcuts. Mod_rewrite needs this option turned on to function, so depending on your configuration you may or may not need this option in your .htaccess file. My site has it on by default, but I've included it here for completeness' sake.

RewriteEngine On

This line turns on Apache's mod_rewrite. Mod_rewrite is straight voodoo.

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]

The RewriteCond directive defines a rule condition. %{HTTP_HOST} starts the rule by saying we want to look at the Apache HTTP_HOST environment variable (e.g "www.example.com" or "example.com" in our case.) The next section is the regular expression we want to test. If that regular expression resolves to true, then we want to run the next line, the RewriteRule on the requested file. It's actually a very simple regular expression. I'll go through it element by element just in case. ^ indicates the start of the string. This is the important part as we only want to redirect if the domain doesn't start with "www." So, what this does is test if the HTTP_HOST starts right in on the domain name. The next interesting part, after the domain name is the \.com$ section. The \. is simply the "." being escaped since the "." character has special meaning in a regular expression. The $ indicates that "com" should be at the end of the string. The [nc] at the end indicates "no case," which makes the rule case insensitive.

RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

This is where the rewrite happens. The first bit (^(.*)$) is a regular expression that grabs everything (.* matches any character zero or more times- in other words anything and everything) from the beginning (^) to the end ($) of the requested URI (everything after http://example.com/) and captures it in a back reference (that's what the () around the .* does.) The next part is the URL we're rewriting everything to. It starts with our target domain (notice the www) followed by that back reference ($1) which contains the requested file. The last part [R=301,L] tells Apache that the Redirect is a 301 and the L tells Apache that's the Last rule. This stops the rewriting process.

There you have it. There won't be a ton of stuff like this in this series, but it's always a possibility, so don't be too surprised if more Apache stuff turns up in the future.

And please, since this isn't my specialty by any means, correct anything that I bungle.

Code I Like: A JavaScript Object as an Argument for a Function

This will hopefully be the first of a continuing series of smaller code articles where I share techniques I (and my team) use on a daily basis. I take this stuff for granted so I think it might be beneficial to share since (a) I might be able to improve what I do by receiving feedback on techniques I use and (b) some of the things I do, while old hat to me, might be new and useful to other people in the field.

We'll see how it goes.

With that short into out of the way I wanted to start off with a bit of JavaScript that I really appreciate, namely using a JavaScript Object as the argument for a function when multiple options are possible.

//Here's what a function call looks like

document.getElementById("myObject").onclick = doSomething(
//here's the object
	{
		//I'm using 3 options here
		file: "/_assets/images/object.jpg",
		messageText: "Objects sure are swell",
		newUrl: "/object.php"
	}
);

//and here's a snippet of the function definition
function doSomething( options ) {
//here we either use the arguments supplied in the call
//or  fall back to defaults.
//notice how the order is off and how callback
//was never supplied in the function call
	options = {
		file: options.file || "",
		callback : options.callback || function(){},
		newUrl: options.newUrl || "http://www.google.com/",
		messageText: options.messageText || "You love Objects"
    };
//stuff happens
};

Why do I like this? Two things:

  1. I don't need to remember the order of arguments and I don't need to supply blank arguments if I'm not using one. I can't tell you the number of times I've messed up the order of arguments and cased an error which I then had to do a couple of minutes of research to fix. I still do it with the addClass, removeClass, hasClass, toggleClass suite I use pretty much every time I write JavaScript and that's only two arguments. If I converted those to a single Object it would be grand since I know I'd remember obj (my default Object argument name) and className.

    …and forget about remembering where to put unused arguments. That's the pits.

  2. It's conceptually much clearer. Organizationally it's much cleaner to me (especially the way the defaults are spelled out right at the top of the function) and the Object labels take any guesswork out of the arguments when the function is called. I know exactly what I'm doing when I call a function defined this way. Compare the Object pattern to this classic:

    "MM_swapImage('Image1','','/img/newImg.jpg',1)"

    Quick, without referring to anything else, what's going on there?

    Sure, the first is the image name and the third is the image name, but what are the other two? Off-hand I'd have no idea and that's one of the most common blocks of code on the internet. Compare that to an object version:

    swapImage( {
    	target: 'Image1',
    	swapFrame: "",
    	fileName: '/img/newImg.jpg',
    	preload : 1
    });

    That brings clarity, right? Stunning clarity for me as I never knew what that always-blank second argument was.

And there you have it, the first installment. There will be a lot of CSS and HTML in this series as well, so if they float your boat as well please keep your eyes peeled.