The
Performance Navigation Timing API
Show archive.org snapshot
allows reading how the current document was loaded.
All major browsers support it.
Usage
You can query navigation entries from the performance API.
They carry a
type property
Show archive.org snapshot
which can be
-
navigate-- followed a link, or opened the page directly (bookmark, or by entering the URL) -
reload-- reloaded manually, or through a programmatic reload likelocation.reload() -
back_forward-- browser loaded page through forward/back buttons -
prerender-- loaded in the background via the Speculation Rules API Show archive.org snapshot
Example:
const navigationItem = window.performance?.getEntriesByType('navigation')[0]
const wasReloaded = navigationItem?.type === 'reload'
SPA quirks
Applications using single-page application frameworks like Angular or Unpoly intercept routing on the client side to avoid full pageloads.
Because the Performance API tracks the document, your navigation entry remains unchanged in such applications.
If a user reloads the page, navigates to four different SPA views, and then triggers your check, the type will still report a reload.
If you need to trigger an action on the initial reload, guard it like so:
// When the application boots:
let consumedReload = false
// Later:
const wasReloaded = window.performance?.getEntriesByType('navigation')[0].type === 'reload'
if (wasReloaded && !consumedReload) {
consumedReload = true
// whatever you do for a reload
}