3 January 2008

Asynchronous JavaScript Part 1 - ADIJ

This is the first in a series of posts regarding asynchronous JavaScript techniques and tools.

In this edition, I will introduce ADIJ. I will ultimately provide code and examples for each of the tools I recommend using.

The What
Asynchronous DOM Injected JSON or ADIJ is what I have termed a fairly common technique found today for getting data from a server using JavaScript in an asynchronous fashion. This technique is more commonly known as the script tag hack.

The How
Its a very simple technique which involves simply adding a script tag with a valid src attribute to the DOM tree. When the script tag is added to the document, the browser will make a request to the URL specified in the src, and load the returned content which will be interpreted and executed immediately.

The Why
I have found ADIJ most useful thus far in mapping mashups. The data returned will normally be in JSON format and this is efficient for parsing and adding points to a map. But the technique can work very well for any public data which needs to be delivered asynchronously to the browser.

Any issues?
Any data returned using ADIJ can be intercepted and in theory, scripts can be injected into your page. However, I normally ensure that I only accept valid JSON containing Objects and Strings. I would never execute a function returned by this technique. This is not a major issue, but one to be aware of. Only ever use ADIJ for fully public data, never for secure data. Be aware that all cookies are provided when the request is made.

Why ADIJ?
ADIJ is more than just a silly name for the script tag hack. ADIJ is a helper object which can allow you to send multiple requests on demand and receive valid JSON data back with co-operation from the server.

Using ADIJ, you provide a handler function (similar to the callback in AJAX) which will receive the JSON data when the request completes successfully. The ADIJ object will manage your requests and handle all the responses for you, ultimately passing the response back to your specified handler function.

The ADIJ object provides a powerful first item in your asynchronous JavaScript toolkit.

In part 2 of this series I will go through the ADIJ object and provide an example.

1 comment:

Neil Mosafi said...

Nice! I'm looking forward to you posting the code so I can do some integration with ASP.NET web services!