javascriptdom-eventsasp.net-ajax

How to do page initialization functions in ASP.NET AJAX?


There seem to be a number of weird things one could do if one wanted, for hooking up page-load type events. Here are some specific questions:

  1. I know about the auto-hooked-up pageLoad function. Are there any others like it?
  2. Where do I hook up events like those from, e.g., Sys.Application.add_init or Sys.WebForms.PageRequestManager.getInstance().addPageLoading?
  3. What's the difference between the first two of those and pageLoad, if any?
  4. Rather importantly, what is the "correct" way to be sure that the ASP.NET AJAX files are all loaded before you start hooking up event handlers, processing the page, etc.? My current approach is to use the auto-hooked-up pageLoad to hook up the rest, but this seems kind of hacky.

Solution

    1. The built-in pageLoad function is just a shortcut to the Sys.Application.load event. There is another one - pageUnload. Find more info here.
    2. You can hook those events up almost whenever you like - using the pageLoad function, invoking the add_init/add_load method inside a script block or calling ScriptManager.RegisterStartupScript from server-side. Just make sure you call that JavaScript within the form tag (see #4). By default all those events occur after the page is loaded so your code should have already been executed by then.
    3. Technically there should be no difference between using pageLoad and the load event - the first is just easier to hook up.
    4. By default the ASP.NET Ajax script files are rendered just after the beginning of the form tag. This means that those files will get loaded before any other JavaScript statement defined within the form tag gets executed.