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
- window.onload = function() {
- init();
- doSomethingElse();
- };
- <html>
- <head>
- <title>onload testtitle>
- <script type="text/javascript">
- window.onload = load;
- function load()
- {
- alert("load event detected!");
- }
- script>
- head>
- <body>
- <p>The load event fires when the document has finished loading!p>
- body>
- html>
Комментариев нет:
Отправить комментарий