Navigation consists of two main stages, whether triggered by a link click or a page refresh.
During the initial stage of navigation, the current page does not immediately terminate. The onbeforeunload
event is triggered, allowing JavaScript to continue executing normally, which includes sending AJAX requests. The browser sends an HTTP request for the new page URL and waits for a response.
Depending on the server's response, the old page may continue running if a 204 Not Modified
status code is received. There may also be redirects involved, further delaying the loading process. It may take some time before the browser receives enough of the new HTML page to begin rendering it.
Only after this stage, the onunload
event is fired, terminating the previous page, aborting any ongoing AJAX requests, and displaying the new page. At this point, any scripts from the previous page will no longer be running.