Run, the DOM is coming!
Before I get started, I’ll make two things clear: 1) when I say “jQuery”, I mean any library / framework; 2) both jQuery and Jonathan Snook are fabulous.
The DOM is, without a doubt, the most maligned aspect of front-end web development. Whenever a non-web developer tries their hand at JavaScript, its probable that, after a few hours of tinkering, they’ll start cursing under their breath at the verbose & obscure API. Give them a few days, and they’ll have discovered some annoying cross-browser differences. At the end of the project, the majority will have given up and slapped in a call to jQuery and some 3rd party plugins to do the dirty work.
I don’t blame them, one little bit. On the other hand, front-end developers – who have experience in overcoming the various problems web coding throws at them – all to often fail at the same hurdle, and I don’t think this is a good thing for web development in general.
Striking the balance
When creating a piece of work that requires some JavaScript, there is often a choice presented to the developer(s). One option is to write all (or most of) the code from the ground up, while another is to use a library such as jQuery to do the heavy lifting. There are a whole range of factors to influence the decision, including (but not limited to):
- Skills. If the team isn’t that hot on JS, its a safe bet that custom code will be trickier to create.
- The project. Starting from scratch gives you options, whereas building upon existing work often means you’ll have to make do with what’s already there.
- Purpose. jQuery could be a good choice for UI enhancements, but perhaps not so great for data presentation.
- Maintenance. If its a large project, using a well-known library makes it easier for new team members to pick up where you left off.
- Time. Its always precious, but if you’re facing a deadline then libraries might make the difference.
You get the idea. Its an important decision to make, because once you commit down one route, going back can be painful. While it differs from project to project, I tend to opt for the custom code route. Why? I think there are great benefits to writing JavaScript code rather than jQuery code (the difference is vast). You’ll build a deeper understanding of the language, you’ll learn how and when to make the correct optimisations; in short you’ll be a better programmer.
All front-end developers have to make this call, but I find that many opt for the jQuery route when they really shouldn’t.
The problem with libraries
The quality and choice of JavaScript libraries nowadays is huge. Each have their own pros and cons, but all have the same fundamental flaws. The days of copy/pasting code snippets from random websites are mostly gone, and so a novice now has at least a chance of using good-quality, well written & tested code in the form of jQuery and 3rd party plugins. Unfortunately, its so easy to do that developers often do the same – search the plugin repository for something to do the job, call in jQuery and move on.
Besides not learning how the code actually works, this can needlessly increase the page footprint for the user. Case in point? Readers of Jonathan Snook’s Simplest jQuery Slideshow are falling over themselves to comment on how concise his solution is (its very small indeed), but almost no-one pointed out that it required users to download the entire jQuery codebase to perform a simple fade effect.
One comment went like this:
I shudder at the thought of seeing this code written out with native DOM methods, and I shudder again at the thought that someone thought that would be preferable.
Sorry, but front-end developers really should be able to write a simple slideshow themselves. At a time when “making the web faster” is gaining traction, I would have thought that developers would realise libraries are not always the best option. CDNs (content delivery networks such as Google Code) might improve things for some users, but certainly not the majority. A quick look through by bookmarks shows multiple instances of varying frameworks – and these are technical sites whose developers are probably aware of CDNs.
The problem with the DOM
If libraries are not always a good choice, then the alternative is going native. More often than not, this will involve getting down and dirty with the DOM. There are several problems with the DOM; here are the main offenders as I see them:
- Obscure, incomplete API. A common complaint is ‘if there’s
insertBefore(), why noinsertAfter()?’ - Slow. DOM methods are notoriously sluggish on older browsers, and can impact performance if you’re not careful.
- Varied implementations. There are more browser differences here than you’ve had hot dinners.
- Verbose. Compared to jQuery, native DOM code ain’t pretty.
(Of course, using a library doesn’t make these problems disappear; some things are optimised and others are simply hidden away).
It may seem like a daunting task to build something useable with the DOM, but for many cases, its not. I recently wrote something very similar to the slideshow mentioned above.
(function(){var fQ=2, dQ=4, q=document.getElementById('images').getElementsByTagName('img'), lQ=q.length, cQ=lQ-1, start, delta, f=!!q[0].filters;fQ=1/(fQ*1000);dQ*=1000;var now=function(){return +new Date;};var alpha=function(n,a){if (f){n.style.setAttribute("filter", "alpha(opacity="+(a*100)+")");}else{n.style.opacity=a;}};var next=function(){q[cQ].parentNode.insertBefore(q[cQ], q[0]);alpha(q[0], 1);setTimeout(fade, dQ);};var fade=function(){start=now();setTimeout(fadeStep,13);q[cQ-1].style.display='block';};var fadeStep=function(){delta=now()-start;if (delta < fQ){alpha(q[0], (100-(Math.floor((fQ*delta)*100))/100);setTimeout(fadeStep,13);}else{alpha(q[0], 0);next();}};setTimeout(fade, dQ);})();
I won't go into detail here, but suffice to say this code uses three DOM methods, some core JS, simple maths and a sprinking of CSS manipulation to get the same effect, with only one instance of object detection to cater for browser differences. Its by no means perfect and could be greatly improved, but weighs in at around 600 bytes when packed. That's 19Kb less than Snook's plugin + jQuery combined. And while it may be less humanly readable, discovering how the script works is an easier task - ask a novice to crack open the jQuery source and watch them weep.
Stop and think
If the website / app in question already used jQuery for other tasks, then its probably a no-brainer - plugins offer great benefits for little cost. But if you've been given a new project, think about what's best, don't jump on the jQuery bandwagon right away. Furthermore, if you're writing about a plugin or library, it's a good idea to mention the alternatives. It might seem obvious to you, but your readers may not realise or care about the downsides.