Hook a javascript event to page load

前端 未结 5 660
感情败类
感情败类 2020-12-03 10:02

I have an aspx that has the following javascript function being ran during the onload event of the body.


相关标签:
5条回答
  • 2020-12-03 10:39
    window.addEventListener("load", function() {
        startClock();
    }
    

    This will invoke the startClock function at page load.

    0 讨论(0)
  • 2020-12-03 10:40

    Insert this anywhere in the body of the page:

    <script type="text/javascript">
    window.onload = function(){
        //do something here
    }
    </script>
    
    0 讨论(0)
  • 2020-12-03 10:40

    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() {
        // ...
    });
    
    0 讨论(0)
  • 2020-12-03 10:48

    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

    0 讨论(0)
  • 2020-12-03 10:48
    Page.ClientScriptManager.RegisterStartupScrip(this.GetType(), "startup", "startClock();", true);
    

    or using prototype

    document.observe("dom:loaded", function() {
      // code here
    });
    
    0 讨论(0)
提交回复
热议问题