admin管理员组文章数量:1426041
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 badges3 Answers
Reset to default 2Taken 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>
本文标签: aspnetReplacing bodyonload in a user controlStack Overflow
版权声明:本文标题:asp.net - Replacing body.onload in a user control - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745402098a2657084.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论