Hook a javascript event to page load

假如想象 提交于 2019-11-27 21:57:41

If you don't want to explicitly assign window.onload or use a framework, consider:

<script type="text/javascript">
function startClock(){
    //do onload work
}
if(window.addEventListener) {
    window.addEventListener('load',startClock,false); //W3C
} else {
    window.attachEvent('onload',startClock); //IE
}
</script>

http://www.quirksmode.org/js/events_advanced.html

Insert this anywhere in the body of the page:

<script type="text/javascript">
window.onload = function(){
    //do something here
}
</script>

The cleanest way is using a javascript framework like jQuery. In jQuery you could define the on-load function in the following way:

$(function() {
    // ...
});

Or, if you don't like the short $(); style:

$(document).ready(function() {
    // ...
});
Page.ClientScriptManager.RegisterStartupScrip(this.GetType(), "startup", "startClock();", true);

or using prototype

document.observe("dom:loaded", function() {
  // code here
});
window.addEventListener("load", function() {
    startClock();
}

This will invoke the startClock function at page load.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!