Sys.Application.add_load != window.onload

Posted on March 01, 2007  |  

Posted in Development

1 comment

I remember seeing a sample which used Sys.Application.add_load to attach a function you’d normally want to run upon window.onload. It went like this:

function initFoo () {
  // Initialization code here...

Sys.Application.add_load (initFoo);

Having browsed the MS AJAX Library source code, I figured the Sys.Application provided a convenient event hook indeed since the class tapped window.load and window.unload for you:

Sys.UI.DomEvent.addHandler (
   window, "unload", this._unloadHandlerDelegate);

Sys.UI.DomEvent.addHandler (
   window, "load", this._loadHandlerDelegate);

To my surprize, initFoo was getting called on every AJAX callback. I figured there was no way get window to fire its onload event several times, so the Sys.Application class must’ve been involved a lot more than I thought.

The remedy is to either hook into window.onload directly:

Sys.UI.DomEvent.addHandler(window, "load", initFoo);

or avoid multiple initializations:

function initFoo () {
  var prm = Sys.WebForms.PageRequestManager.getInstance();

 if (prm.get_isInAsyncPostBack())

 // Initialization code here...

To me, the former looks cleaner and less kludgy than the latter.

1 comment

on July 29, 2008

Thanks for this blog post. I ran into a problem were i have a tab control loading sever update panels and i needed a function to load one time each however using Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded
caused the method to be loaded for each panel even adding flow statements to check the panel loading it still ran x amount of times.

using this method this events occures before the tab panel control has been added to the component list meaning $find returns null. this happens with both


do you know of any event that can be hooked using this that occures after the components have loaded but before render?