Substitute for onLoad with WebParts

I’ve got a project where I’m using google maps within an ASP.NET web part in an update panel. The google maps code requires you to run some javascript as soon as the page loads. Usually people put this in <body onload=x> or use javascript: window.onload=x, but when I did those either the method wouldn’t run, or web parts would get messed up. I’m guessing because there’s some web parts javascript that needs to run at page load, and since you can only assign one method, they were interfering with eachother.

I tried just running the google maps initialization script after I write all the needed elements to the page, but then I was randomly getting the dreaded IE error “Internet Explorer cannot open the internet site. Operation Aborted.” The common fixes to this error suggest calling your initialization script with an onload trigger (not possible for me as described above) or moving your script to the bottom of the page, outside of the body tag.

Sounds like an easy fix, but since I was using web parts within update panels I had to use ScriptManager.RegisterStartupScript in order to inject the code, which didn’t allow me to place exactly where the script was being placed. After long hours of trying many many workarounds, I finally found about the PageRequestManager pageLoaded event. It’s a javascript class that is available when you use asp.net’s ajax, and it can be used to register functions that should be triggered once the page is loaded. Here’s the javascript you need:

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(myFunctionToRunOnLoad);

It took me forever to find this, I wish it was documented more. Hopefully it solves your problems!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *