FE Interview Hub
Browser InternalsBasic

Explain when DOMContentLoaded, load, beforeunload, and unload are fired

AI Practice

Page lifecycle events

The browser fires four key events as a page loads and unloads:

DOMContentLoaded

  • When: fired as soon as the HTML document has been fully parsed and the DOM tree is built. Does not wait for stylesheets, images, or iframes to finish loading.
  • Target: document
  • Use cases: DOM manipulation, initialising JS logic, binding events
document.addEventListener('DOMContentLoaded', () => {
  console.log('DOM is ready');
});

Note: a render-blocking <script> in <head> (without async/defer) will delay this event.

load

  • When: fired after all resources on the page (images, CSS, fonts, iframes…) have finished loading.
  • Target: window
  • Use cases: reading image dimensions, running logic that depends on every asset being available
window.addEventListener('load', () => {
  console.log('All resources loaded');
});

beforeunload

  • When: fired when the user is about to leave the page (closing the tab, refreshing, navigating away). You can intercept at this point.
  • Target: window
  • Use cases: warn the user about unsaved changes
window.addEventListener('beforeunload', (e) => {
  e.preventDefault();
  e.returnValue = ''; // triggers the browser's built-in "Leave site?" dialog
});

Modern browsers ignore custom message strings and show a standard dialog.

unload

  • When: fired while the page is being unloaded (the user has already confirmed they are leaving).
  • Target: window
  • Use cases: cleanup (clear timers), fire-and-forget analytics with sendBeacon
window.addEventListener('unload', () => {
  navigator.sendBeacon('/analytics', data);
});

You cannot do heavy work or stop the unload here. Mobile browsers may skip unload for BFCache — prefer pagehide instead.

Order of events

HTML fully parsed
  └─ DOMContentLoaded  (DOM ready)
       └─ load  (all resources ready)
            └─ [user navigates away]
                 ├─ beforeunload  (ask user to confirm)
                 └─ unload  (page is being torn down)

Comparison

Event Target Waits for resources Can block navigation
DOMContentLoaded document No No
load window Yes No
beforeunload window Yes
unload window No

✦ AI Mock Interview

Type your answer and get instant AI feedback

Sign in to use AI scoring