Sunday, May 13, 2007

AJAX frameworks are NOT pointless

This was a response I posted to Slashdot a week ago. Why am I reposting it here? It's because I found my own post back when I was searching on Google today. In particular, I found other bloggers and websites bookmarking or discussing the stuff I wrote. So I guess the stuff I wrote was useful? Then maybe you want to know about it too. So, here it is:



There are many little funny things that just happens when you're coding a web application in JavaScript without a framework/library/toolkit helping you. Unless you're really an AJAX/JavaScript wizard, coding an AJAX-enabled web application on your own and mixing online code receipts is a very dangerous thing to do.



Browser inconsistencies

This is the most obvious one, but only the entry to the rabbit hole. If you are not familiar with the example (maybe not exactly the same, but any AJAX web developer worth his salt should have seen one like that) I give below, then please, PLEASE, do yourself, your fellow developers and your users a favor, resist the urge to hack things together for once, use a mature AJAX framework.

An important part of AJAX is that you need to update what is displayed on the web browser in the client side (by JavaScript), without refreshing the page. This implies that you're very likely to have to create and destroy DOM nodes on the fly. Now, how do you create a radio button in JavaScript?

How about...

var node = document.createElement("input");
node.type = "radio"
node.name = ...
node.value = ...
That's what you would do if you follow the DOM standard. But sorry, this does not work. Try to create a radio button with the above code segment in Internet Explorer 6, you'll get a broken radio button - you can't select it. The correct way to create a radio button by DOM manipulation is described in this MSDN article [microsoft.com]:

newRadioButton = document.createElement("<INPUT TYPE='RADIO' NAME='RADIOTEST' VALUE='Second Choice'>")



Memory leaks

The last one was easy. Do you know you can make a web application that leaks memory like a sieve in Internet Explorer 6 by making a simple circular reference like the following one?

var node = document.createElement("div");
node.someAttr = node;
If you're a good programmer, I might have sounded an alarm in your head right now - any circular references involving DOM nodes in IE6 results in memory leaks that persist after URL changes or page refreshes - unless you use an AJAX toolkit that takes care of the issue for you. Have you assigned a DOM as an attribute value under another DOM node in the past? Yes? Then you'd better check your web application for memory leaks with Drip [outofhanwell.com], now.

What's more, it's not just assigning DOM nodes as attributes that would result in memory leaks, closures in JavaScript can also form circular references and cause memory leaks. What makes closures particularly dangerous is that circular references with closures are not easy to spot. For example, the following code segment leaks:

var node = document.createElement("div");
var clickHandler = function(){};
node.onclick = clickHandler;
Looks innocent enough, but you've already formed a leaky circular reference here. node->clickHandler->node.

For more information about memory leaks under IE6, read these:

Mihai Bazon's blog entry [bazon.net]
MSDN's lengthy and confusing description of the problem [microsoft.com]



The XMLHttpRequest object is not as simple as you think

Much of the magic of AJAX comes from the XMLHttpRequest object (or its ActiveX equivalent, or an iframe, etc.), right? Sure. If you're only doing something simple via AJAX (like, updating the server time), then you can just copy an XMLHttpRequest code snippet from sites like this [apple.com] and hack away, right?

Wrong! Those XMLHttpRequest code snippets are one of the very reasons why people are thinking AJAX as a hack - it sometimes doesn't work! The XMLHttpRequest code snippet given on Apple's site can be broken in commonly encountered situations, and you can simulate that yourself:

  1. Write a simple AJAX web application that retrieves and displays the current server time on a web browser using Apple's code snippet.

  2. Test it yourself under normal conditions. So it works and it's safe to use, right? Let's see...

  3. Change your computer's routing table such that you can have no route to the web server.

  4. Now test your application again in Firefox. Your application should fail. But does it fail gracefully? No. You see an error message in Firefox's error console stating that the XMLHttpRequest object's status attribute cannot be read. If you have coded something to handle AJAX request failures, your handler won't be called.

Why is that happening? It is because, any socket errors happening during an AJAX request will cause the onreadystatechange handler to be called under Firefox, yet the status attribute cannot be read. Reading it causes a JavaScript error and stops JavaScript execution (unless you add a try...catch... block there, but that assumes you already know about the problem so it's moot)! Under Internet Explorer, reading the status attribute in the same situation gives you the socket error code instead. Don't know about these stuff? Please, use a mature AJAX framework.



Performance problems

Coding AJAX applications is just like writing things in C++ or Java - so long as you're using efficient algorithms, your application should run fast, right?

Of course, you are wrong again. Let's say... in some part of your application, you want to concatenate a lot of string fragments together to form a long string in a for loop, how do you do it? How about...

var targetString = "";
for(var i=0;i<someArray.length;i++)
targetString += someArray[i];
That's the way most programmers would think of, intuitively. But the performance of that sucks under Internet Explorer. The correct way to combine strings under JavaScript is to use the Array.join() operation. You can read more about this here [comet.co.il]. The optimization I talked about is also implemented in Dojo Toolkit (kudos to Alex Russell), and I believe any reasonably robust AJAX framework should have it too. Not knowing about such problems, had you hacked together a fairly sophisticated AJAX web application yourself, you would be running into performance hell sooner or later.

Taking 646ms to combine strings still doesn't sound very slow for you, right? There are many more performance traps in JavaScript. Do you know there's a very significant performance difference between the following two code snippets?

First code snippet:

// placing 5000 "Hello World" messages in random positions
for(var i=0;i<5000;i++)
{
var node = document.createElement("div");
node.appendChild(document.createTextNode("Hello World!"));
document.body.appendChild(node);
node.style.position = "absolute";
node.style.left = parseInt(Math.random() * 800) + "px";
node.style.top = parseInt(Math.random() * 800) + "px";
}
Second code snippet:

// placing 5000 "Hello World" messages in random positions
for(var i=0;i<5000;i++)
{
var node = document.createElement("div");
node.appendChild(document.createTextNode("Hello World!"));
node.style.position = "absolute";
node.style.left = parseInt(Math.random() * 800) + "px";
node.style.top = parseInt(Math.random() * 800) + "px";
document.body.appendChild(node);
}
The only difference between the two code snippets is the placement of the document.body.appendChild() line. But if you actually test them out, the second code snippet is much faster, under both IE and Firefox. The performance difference has nothing to do with your algorithms - you just shuffled one line of code around; it has to do with how the browser render the randomly placed DIV nodes. Ever wondered why your hacked together web application is taking half a minute running JavaScript after all the files are loaded?

So, unless you're already a programming god or don't mind spending lots of time solving bugs that you shouldn't have solved; you really, really should use some of these AJAX frameworks if you're making anything fairly sophisticated with AJAX.

68 comments:

Anonymous said...

xanax alprazolam xanax hair drug screen - much do 2mg xanax cost

Anonymous said...

xanax online xanax for public speaking anxiety - xanax side effects tremors

Anonymous said...

generic xanax 1mg xanax good - xanax 3mg online

Anonymous said...

buy tramadol online what dosage tramadol for dogs - tramadol dosage and dogs

Anonymous said...

generic xanax xanax long term side effects - buy xanax online overnight

Anonymous said...

xanax cost types generic xanax - buy xanax online no prescription mastercard

Anonymous said...

buy tramadol online buy tramadol online no prescription mastercard - tramadol hcl 50 mg 319

Anonymous said...

xanax online yellow xanax bars 039 - generic xanax 0.25mg

Anonymous said...

buy tramadol online pet meds tramadol no prescription - tramadol purchase online usa

Anonymous said...

buy cheap tramadol buy tramadol london - tramadol online free shipping

Anonymous said...

generic xanax pictures of generic xanax pills - safe place buy xanax online

Anonymous said...

buy tramadol online buy tramadol online legit - order cheap tramadol-overnight

Anonymous said...

xanax without prescription buy xanax overnight delivery - do xanax 2mg look like

Anonymous said...

generic xanax xanax yellow bar - 0.5mg xanax and alcohol

Anonymous said...

carisoprodol 350 mg carisoprodol 350 mg cost - carisoprodol dan 5513 side effects

Anonymous said...

buy tramadol online illegal buy tramadol online - buy tramadol topix

Anonymous said...

order tramadol online tramadol 50mg how many can i take - tramadol for dogs generic

Anonymous said...

xanax 1mg xanax withdrawal symptoms webmd - xanax bars like

Anonymous said...

alprazolam xanax green xanax pills s 902 - xanax restoril drug interactions

Anonymous said...

generic xanax is generic xanax the same - xanax online with prescription

Anonymous said...

buy tramadol online purchase tramadol cod - tramadol 100mg sr tablet

Anonymous said...

carisoprodol 350 mg where to buy carisoprodol online - soma = carisoprodol tablets 350 mg

Anonymous said...

buy tramadol online buy tramadol montreal - 100mg tramadol is equivalent to what

Anonymous said...

buy tramadol online tramadol for dogs human use - buy tramadol no prescription cheap

Anonymous said...

cialis online cialis price comparison walmart - cialis online to usa

Anonymous said...

xanax online buy green xanax bars - xanax drug label

Anonymous said...

buy cialis online buy cialis online in usa - cialis for sale

Anonymous said...

cialis online cialis 5 mg best price australia - cialis online andorra

Anonymous said...

buy cialis online buy cialis daily online - cialis 30 day cost

Anonymous said...

buy cialis online buy cialis usa cheap - buy cialis no prescription

Anonymous said...

buy tramadol online buy tramadol online overnight shipping - tramadol ultram side effects

Anonymous said...

http://buytramadolonlinecool.com/#96430 buy tramadol montreal - tramadol ultram same thing

Anonymous said...

buy tramadol order tramadol usa - tramadol 600 mg daily

Anonymous said...

learn how to buy tramdadol tramadol for dogs to buy - tramadol hcl urban dictionary

Anonymous said...

buy tramadol without prescriptions tramadol 50mg buy - tramadol hcl paracetamol tablets

Anonymous said...

buy tramadol buy tramadol online cod no prescription - tramadol hcl 50 mg tablet high

Anonymous said...

buy tramadol buy tramadol from usa - tramadol ultram ingredients

Anonymous said...

http://landvoicelearning.com/#51438 cheaptramadolonline - tramadol dosage acetaminophen

Anonymous said...

tramadol online tramadol overnight no prescription needed - tramadol erowid

Anonymous said...

buy tramadol online cod overnight order tramadol online no prescription overnight - tramadol withdrawal cold turkey

Anonymous said...

buy tramadol online buy tramadol online yahoo - tramadol overdose dog

Anonymous said...

http://landvoicelearning.com/#21906 legal buy tramadol online usa - buy tramadol with mastercard

Anonymous said...

learn how to buy tramdadol buy generic tramadol - tramadol legal to buy online

Anonymous said...

learn how to buy tramdadol tramadol 50 mg high - cheap tramadol no prescription

Anonymous said...

buy tramadol tramadol hcl 50 mg - tramadol high off

Anonymous said...

buy tramadol tramadol 50 mg headache - tramadol 50 mg iv

Anonymous said...

Yоur write-up offеrѕ pгoven
bеnefіciаl to me. It’s quite еducational and you're simply certainly very experienced in this region. You have got popped my personal eyes to be able to numerous views on this particular topic along with intriguing, notable and solid articles.
Look at my site ... Xanax

Anonymous said...

buy tramadol tramadol hcl 50 mg generic - tramadol hydrochloride 100mg used

Anonymous said...

http://landvoicelearning.com/#62431 buy tramadol online without prescriptions - tramadol hcl 50 mg tab amn

Anonymous said...

buy tramadol online tramadol addiction - buy tramadol online without script

Anonymous said...

buy tramadol cod buy tramadol online no prescription needed - tramadol withdrawal no sleep

Anonymous said...

Your report οfferѕ ρrovеn helpful to me.

It’ѕ very іnformative аnd yоu're simply naturally quite experienced in this region. You have got exposed my personal sight in order to different thoughts about this subject together with intriguing and sound written content.
Take a look at my blog post : buy Xanax

Anonymous said...

http://reidmoody.com/#49853 ativan get u high - ativan for alcohol withdrawal

Anonymous said...

ways to buy ativan online ativan r59 - ativan mayo clinic

Anonymous said...

buy xanax online xanax withdrawal panic attack - what does a xanax 2mg pill look like

Anonymous said...

buy xanax online xanax to order online - xanax online legal

Anonymous said...

buy xanax online no prescription buy xanax online for cheap - get prescription xanax online

Anonymous said...

buy tramadol online order tramadol online prescription - street value of tramadol 50mg

Anonymous said...

http://staam.org/#50589 tramadol high dosage - how to order tramadol online no prescription

Anonymous said...

http://ranchodelastortugas.com/#93851 xanax for anxiety disorder - xanax vicodin

Anonymous said...

http://staam.org/#21236 tramadol hydrochloride overdose - buy tramadol now

Anonymous said...

buy xanax online ativan or xanax for anxiety - buy xanax online cheap mastercard

Anonymous said...

buy tramadol online tramadol pictures - tramadol for dogs same for humans

Anonymous said...

buy xanax online xanax drug fact sheet - xanax bars r039

Anonymous said...

buy xanax online mixing xanax and alcohol 2 boards - does xanax show up on employment drug test

Anonymous said...

buy xanax online legally xanax xr high - alprazolam 2mg yellow bar

Anonymous said...

Thе writе-up has ѵerifiеd useful to me.

Іt’s rеally helрful and you're naturally very educated in this field. You have got popped my sight to varying views on this specific matter together with intriguing and reliable articles.
Feel free to surf my web blog :: soma

Anonymous said...

Υοur rеpоrt has proѵen neceѕѕary tо mе pеrsοnally.
It’s really helpful and you're clearly extremely well-informed in this region. You have opened our eyes in order to various opinion of this kind of subject matter together with intriquing, notable and sound content.
Look into my blog post - xanax online