Self Optimizing AJAX Object
In 2007 I wrote a self contained AJAX object that supports asynchronous and synchronous access with PUT and GET methods, text and XML and XSL tranforms. The impetous for making certain methods of the object self optimizing came from an blog post by Peter-Paul Koch on @media Ajax 2007 Day 2. The example used by Dan Webb is the following addEvent function.
function addEvent(obj, evt, fn) { if (document.addEventListener) { addEvent = function (obj, evt, fn) { obj.addEventListener(evt, fn, false); } } else if (document.attachEvent) { addEvent = function (obj, evt, fn) { obj.attachEvent('on' + evt, fn); } } addEvent(obj, evt, fn); }
Rewriting a function at runtime is a wonderful way to avoid object detection and improve performance. From Peter-Paul Koch's blog post:
Basically, what happens is that the first timeaddEvent
is called, the function determines whether the browser supportsaddEventListener
orattachEvent
. It then rewrites itself to a new function that uses the detected method to add the event. As a result, we only have to do the object detection once, which is much more elegant than doing it every time.
I realized that an AJAX object was a perfect place to use runtime function optimization. Consider the following createXMLHTTPObject function.