More Client-side fun, and a thank-you

So as I mentioned in my last post, I've been playing around a bit with Virtual Earth and client-side javascript, and being somewhat rusty in this area, ran into a few issues. One of the areas I initially had trouble with was wiring up my javascript functionality so it would run when the page loads.

For the Virtual Earth Interactive SDK, the answer to this is fairly straightforward, they hook the onload event of the <body> element.

Unfortunately, in my case I needed to make this work within an ASP.NET Content control, and since the <body> element exists in the Master page, hooking its onload event didn't make much sense.

So my initial attempts revolved around hooking into the Window onload event and using it to call the function that loads the map. Unfortunately, this simply doesn't work consistently across browsers, and I could have spent hours fiddling with hacks and workarounds, but thankfully was reminded by my co-worker Peter Laudati that our ASP.NET AJAX client libraries already handle the cross-browser compatibility, and also provide a rich event handling infrastructure (docs here) that is similar to what ASP.NET provides.

The solution ended up being simply adding a handler for the ASP.NET AJAX-provided pageLoad handler, which is wired up by using the appropriate function signature, like so:

function pageLoad(sender, args) {

Of course, to support this, you need to add a ScriptManager control to your page, as it is the ScriptManager that provides the server-side logic to determine which scripts need to be sent down to the client given the browser that's making the request, and the functionality you have enabled in the page.

So really it's as simple as adding one control, writing one event handler, and then I can easily call the Virtual Earth map control API just as shown in the online SDK. Much simpler than the way I was trying to do it, and my thanks to Peter for setting me straight and preventing me from pulling my hair out doing it the hard way.

BTW, I'm sure that the notion of using available libraries instead of writing it yourself is probably obvious to some of you out there. And it should have been obvious to me...but I'm sure many of you have experienced that moment when you're busy trying to solve a given problem, and you're deep enough in the weeds that you can't quite see there are easier solutions available. That's why it's good to have teammates to smack you around a bit when you're being dim.

Technorati Tags: AJAX, cross browser, javascript, tips and tricks, virtual earth