window.onload from before

来源:互联网 发布:网络存储器怎么用 编辑:程序博客网 时间:2024/05/18 15:52

http://www.peterbe.com/plog/window.onload-from-before

In an DHTML solution I've been working on I need to tap into window.onload and append my own function in there. The code looked something like this:

<script>function foo() { alert("foo"); }window.onload = function() { foo(); }</script>... more HTML junk ...<script>function bar() { alert("bar"); }window.onload = function() { bar(); }</script>

If you run this it will only run the bar() function because it was defined last. Ideally one would want to write something like this in the second chunk of javascript:

<script>function bar() { alert("bar"); }window.onload = function() { foo(); bar(); }</script>

which when you run it does both alerts but it's unfortunate that the second piece of javascript needs to know about parenting code.

My solution requires that any new work on window.onload takes whatever was there into account before. Here's the solution I came up with. It seems to work fine in Firefox (linux, windows) and Internet Explorer (windows).

What I do is that I create a variable of the current window.onload and call it like any other function. It looks like this:

<script>function bar() { alert("bar"); }var prev_onload = window.onload;window.onload = function() { prev_onload(); bar(); }</script>

The advantage here is that in the second piece of code which can come from anywhere on the server, you do not need to know anything about what happened before in the document. This makes it very convenient when writing a very modular website with widgets coming in from different places. Try it if it works on your computer

What do people think?


0 0