Monday, August 13, 2007

AJAX Life cycle

The Ajax lifecycle is more like that of a traditional GUI than a traditional web application, with DOM objects acting like GUI widgets. The script registers event listeners on DOM objects, and manipulates the DOM in response to those events. As part of the event-processing cycle, the server may be invoked. There's actually a slight complication here in that the server calls are asynchronous, so the event-listening phase is split from the event-responding phase.

Here's a typical Ajax lifecycle within the browser:

  • Visit: The user visits a site the usual way, i.e. by clicking on a link or typing a URL.
  • Initialisation The page initially loads. Callbacks are established to handle user input, a loop might be established to continously refresh page elements.
  • Event Loop:
    • Browser Event An event occurs, such as a keypress.
    • Server Request The browser sends a request to the server.
    • ...<Server processes the event>
    • Server Response A moment later, the server responds, and the response is passed into a request callback function, one that was specified when the request was issued.
    • Browser Update The request callback function updates the DOM, including any Javascript variables, according to the response.

Of course, there are plenty of variants. In particular, many events are handled locally and don't actually trigger a trip to the server. Also, some Ajax applications are short-lived and the browser interaction is eventually terminated with the user submitting a form. Others remain to interact with the user as long as they are in the user's browser.

Note that the Browser Event and the Server Request occur in one thread, and the Server Response and Browser Update occur in a separate thread. This is due to the asynchronous nature of the server request. It's actually possible to configure XMLHttpRequest to make synchronous calls, but poor practice as it holds up the user.

0 comments: