最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asp.net - Replacing body.onload in a user control - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Feb 27, 2009 at 16:13 DotnetDudeDotnetDude 11.8k38 gold badges103 silver badges159 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

Taken from http://snipplr./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.

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>

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>
发布评论

评论列表(0)

  1. 暂无评论