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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With