Samstag, November 15, 2008

Extending the initialization sequence of JavaScript behaviors

This topic was recently discussed in the OpenAjax group and here is the implemented solution for the AjaxEngine framework. The consensus was to solve the initialization problem on the application level and not within the OpenAjax hub.


When multiple components resist side by side on the same page the initialization sequence of the components can become critical for the page to work as expected. Therefore the JavaScript behavior mechanism supports 3 phases of initializing the application when a page loads:

  1. The optional init() method is called first for every control that was initialized by LoadBehavior. This method should contain all initialization code that puts the control in a fully working state. Especially the control should register for any interesting OpenAjax event.
  2. The optional initstate() method is called then and allows the control to inform other controls about their existence and publish state information by using OpenAjax events or direct method calls if appropriate.
  3. The optional afterinit() method is called at last to controls can finish the setup where all other controls are also working.

All controls can participate in the initialization phases by implementing the calls. They are all optional. All 3 methods will be called when the onload event is raised for the window object.

The term method

Another method named "term" can be defined in the JavaScript prototypes to implement a method that is called just before a page unloads. There is a real need for implementing code just before all HTML and JavaScript objects are thrown away in Microsoft Internet Explorer, because there is a well known problem with the memory management used by the HTML DOM and JavaScript. Both object libraries do have their own garbage collector implementation and in some cases circular references between objects of both worlds are not properly detected and memory will not get freed and useless memory consumption is the unwanted result.

The best solution against this “design weakness” is to set all references of JavaScript variables to HTML elements to null in this method.

There is also a great tool and some more background information available that helps to detect this kind of memory leak named Drip available at and is a definitive TO-DO when supporting older browser versions of IE.