Imagine an HTML element like the following:
<a onClick={() => console.log("side effect that needs to fire before the redirect"} href="yourlink.com">Click me</a>
Here the event onClick gets executed before the user is redirected. Is this always the case or is this undefined or does this depend on the browser?
CodePudding user response:
Is this always the case...
Yes, the default action of an event (such as following a link), if any, is not triggered until the event handlers have been called, not least because the event handlers could prevent it from happening by calling preventDefault
on the event object.
Beware, though, that when the page is being left, (almost) any outstanding asynchronous work will be terminated. So your event handler can't (for instance) send a standard ajax request to the server; when the handler returns, that work is still in progress, and will be terminated when the page is torn down. (One exception to that is a beacon.)