2

I have a function, foo, that I would like to add to window.onload however my problem is that there is already another function, bar, set to window.onload. How can I get both functions attached. I have no access to change the logic of how bar is added to window.onload therefore I can’t use the paradigm addEvent(…) . Would something like the following work in all cases?

<script>
$(window).load(foo(){
//my code here
});
</script>

//lots of html
//potentially this happens before or after my above script

<script>
window.onload = bar();
otherFunction(){
//other function code here
};
</script>
Nosrettap
  • 10,940
  • 23
  • 85
  • 140
brucebomber
  • 93
  • 1
  • 8

3 Answers3

5

This is a non-issue since you're using jQuery. You can call $(window).load(...) multiple times and it won't stomp out previously-bound event handlers.

This function takes an anonymous function as a parameter, which is executed once the load event is fired. e.g.

$(window).load(function() {alert('the window has loaded');});

JQuery Documentation of the .load() handler: https://api.jquery.com/load-event.

For reference, the equivalent "vanilla" JS would be to use window.addEventListener.


Update

Instead of the .load event, use .on('load,':

$(window).on('load', function() { alert('This is better'); });

See https://stackoverflow.com/a/37915907/361842 for more.

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
3

A function can't be appended to, however you could use addEventListener and then register several functions for the load event:

window.addEventListener("load",a);
window.addEventListener("load",b);
function a(){
  alert("one");
}
function b(){
  alert("two");
}
Tom
  • 4,422
  • 3
  • 24
  • 36
0
<!doctype html>

<html>
  <head>
    <meta http-equiv='content-type' content='text/hmtl; charset=utf-8'/>
    <script type='text/javascript'>
      window.addEventListener("load",foo);
      window.addEventListener("load",bar);
      function foo(){
        alert("this");
      }
      function bar(){
        alert("that");
      }
    </script>

  </head>

  <body>

  </body>
</html>
dano
  • 1,043
  • 1
  • 6
  • 11
  • why did you minus me? And a better solution is to call something like 'initPage()' function on load and then call whatever functions you want from that – dano Sep 04 '13 at 03:21