Friday, November 20, 2009

Richfaces Ajax Polling - Beware

The essence of web 2.0 technology is the Ajax functionality or something similar. Simply put Ajax is just a way to invoke a server side function without submitting or invoking a HTTP POST/GET on the entire page. When the function is complete Java Script is used to update or re-render a part of the screen without leaving it. The main advantage of Ajax if implemented correctly is a better user experience.

  • Users can trigger an action and still continue to work on a web page while there action is being fullfilled.
  • Users can receive immediate validation while completing a form of data like an application, request or servey etc.

Richfaces JSF library provides a lot of commonly used Ajax features. On such feature is Ajax Polling, which is a way to invoke a server side function not from a users actions, but on a time interval. This functionality is ideal solution for web pages where they have to constantly have the most up-to-date information. Some common examples might be stock quotes or bid updates etc.

With RichFaces taking advantage of this feature very easy, simply by a adding a few lines that look like the following.

<a4j:poll id="poll" interval="1000" enabled="true" rerender="quotes,status">

The above line will refresh two elements with id 'quotes' and 'status' every 1 sec (1000 milliseconds). These elements could anything from Rich:Panel to togglePanels. That is it!

The ease is also the problem in this case. Let me explain, it is so easy, that you might end up using it for everything and sometimes for the wrong reason. The simple criteria that I base my decision is "Do you need server side action for information being polled?". In most cases the answer to this question will be yes, but there might be a few instances where the task can be accomplished on the client side. To trigger a simple client side Java script you will need the following like of JS code.

var x = window.setInterval('dosomething()', 500);

Where 'dosomething()' is a Java script function that is being triggered or invoked every half a second (500 milliseconds).
So, if you don't need anything from the server use this approach inorder to avoid all the expensive richfaces rerendering.