суббота, 1 мая 2010 г.

Using window.onload event



Some scripts require that you run something immediately after the web page finishes loading. The normal way to do this is to add an onload attribute to the body tag. You don't have to do it that way though, you can set up a global event handler to do it instead.
Why would you want to use a global event handler instead of just adding the code into the body tag? I can think of two reasons. Firstly by using a global event handler you make it easier to add the code to web pages because you don't have to edit the body tag, if you add the script into an existing external Javascript file attached to your page you may not need to edit the page at all. Secondly some web editors may limit your ability to add code easily to the body tag.



Example

  1. window.onload = function() {  
  2.   init();  
  3.   doSomethingElse();  
  4. };  
  1. <html>  
  2. <head>  
  3.   
  4. <title>onload testtitle>  
  5.   
  6. <script type="text/javascript">  
  7.   
  8. window.onload = load;  
  9.   
  10. function load()  
  11. {  
  12.  alert("load event detected!");  
  13. }  
  14. script>  
  15. head>  
  16.   
  17. <body>  
  18. <p>The load event fires when the document has finished loading!p>  
  19. body>  
  20. html>  

Комментариев нет: