Reputation: 93
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>
Upvotes: 2
Views: 5519
Reputation: 360026
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.
Upvotes: 6
Reputation: 4592
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");
}
Upvotes: 3
Reputation: 1043
<!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>
Upvotes: 0