views:

594

answers:

3

I am refactoring a page that uses <body onload="myJS();"> to a user control. I understand I can do it using server side script registration on load.

If I want to do it on the client side (ascx), how would I do this?

+2  A: 

Taken from http://snipplr.com/view/3116/cross-browser-add-event-listener/

// Cross-browser implementation of element.addEventListener()

function addEvent(evnt, elem, func) {
    if (elem.addEventListener) // W3C DOM
        elem.addEventListener(evnt,func,false);
    else if (elem.attachEvent) { // IE DOM
        var r = elem.attachEvent("on"+evnt, func);

    return r;
}

Use it like this: addEvent(window, your_onload_handler). Or you could just use jquery for this and a lot of other things.

RommeDeSerieux
+2  A: 

Romme's client-side approach is best. But just in case somebody wanted to know how to do it using server-side code in the ASCX file, stick this in at the top of your template:

<script runat="server">

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    string strScript = "myJS();";
    Page.ClientScript.RegisterStartupScript(this.GetType(), "OnLoadScript_" + this.ClientID, strScript, true);
}

</script>
James McCormack
A: 

OnLoad is generally a bad way to initialize JS, because it is only fired when all the resources have finished loading (including any images in the page).

The simplest, and most reliable way to call Javascript that you want to execute when the page finishes loading is to put an inline <script> block into the bottom of your HTML, right before the closing </body> tag:

 <body>
   ... your page here ...
   <script>myJS();</script>
 </body>
</html>
levik
Can you explain why it's bad to init JS after all the resources have finished loading?
DotnetDude
You generally want to defer JS initialization until the page has loaded because you may need to use the page's DOM. Resources like images are most likely not required for your JS to init properly, but if you wait for them it takes longer to start your initialization, making the page seem slower.
levik