Dispose your client objects

Sitefinity CMS uses MS Ajax Script Components everywhere in its backend. That includes widget designers, grids, selectors and the page editor. When writing custom widgets which have client-side functionality, you can also extend them using MS Ajax. Microsoft have introduced a model and conventions on writing script controls that should be taken into account.

One of these conventions is to use the initialize and dispose methods in each script control. Those are called automatically by the framework and serve as an analogue of constructors and destructors in server-side object-oriented programming. A simple script controls looks something like this:

You can see that the initialize and dispose methods are defined by default. They call the base methods of the ASP.NET Ajax Control client object and serve as placeholders, where you can initialize and dispose anything custom in the script control you are implementing. Often developers forget to dispose objects that they use. Since JavaScript is not a compiled language, it is a bit forgiving and doesn’t cause any errors when this happens. You page becomes slow and uses more memory in the browser as a result.

You should be careful and dispose all objects you create in your client components.


When working with client components, you usually create delegates for certain client methods and wire up events using those delegates. This is done to preserve the closure of the script component. The creation of a delegate looks like this:

Here you create a delegate which will invoke the _formSaved method, and assign it to the _formSavedDelegate member. This delegate occupies memory in the browser. In the above snippet, you also it for garbage collection in the dispose method.

You should do the same with all delegates you create in your client components.

Event Handlers

Another thing developers often do in their client compontents is to register event handlers for some things their components do. This is usually done using the $addHandler shortcut method in ASP.NET Ajax. The example below registers a handler for the click event of a link:

Those handlers that you register also occupy memory in the browser when our client component is used. You should always remove handlers when the component is disposed. You can use the $removeHandler shortcut method from ASP.NET Ajax.

Any time you encounter registering such a handler, remember to remove it in the dispose method. This will free up some memory in the browsers of your users, and improve the performance of your application.

Want to learn more?

Sign up for our free beginner training. Boost your credentials through advanced courses and certification.
Register for Sitefinity training and certification.

Was this article helpful?