Page Lifecycle API

Android, iOS and the latest Windows systems can stop background processes autonomously at any time and release system resources in time. In other words, web pages may be discarded by the system at any time. The previous browser API did not take this situation into account at all, resulting in the developer having no way to monitor the system discarding the page.

In order to solve this problem, W3C newly formulated a Page Lifecycle API, which unifies the behavior mode of web pages from birth to uninstallation, and defines new events to allow developers to respond to various transitions of web page status.

With this API, developers can predict the next state of the web page and perform various targeted processing. Chrome 68 supports this API. For older browsers, you can use the compatibility library PageLifecycle.js developed by Google.

Life cycle stage

The life cycle of a web page is divided into six stages, and each moment can only be in one of the stages.

(1) Active stage

In the Active phase, the web page is visible and has the input focus.

(2) Passive stage

In the Passive phase, the web page is visible, but there is no input focus and input cannot be accepted. UI updates (such as animation) are still being performed. This stage can only happen when there are multiple windows on the desktop at the same time.

(3) Hidden stage

In the Hidden stage, the user's desktop is occupied by other windows, and the web page is not visible, but it has not been frozen. UI updates are no longer performed.

(4) Terminated stage

In the Terminated phase, because the user actively closes the window or goes to another page in the same window, the current page starts to be unloaded by the browser and cleared from the memory. Note that this stage always occurs after the Hidden stage, that is, the user actively leaves the current page, always enters the Hidden stage first, and then enters the Terminated stage.

This stage will cause the web page to be uninstalled, and any new tasks will not be started in this stage, and if the running time is too long, the ongoing tasks may be terminated.

(5) Frozen stage

If the webpage is in the Hidden phase for too long and the user does not close the webpage, the browser may freeze the webpage and make it enter the Frozen phase. However, it is also possible that the page in the visible state will enter the Frozen stage if it is not operated for a long time.

The characteristic of this stage is that the web page will no longer be allocated CPU computing resources. Timers, callback functions, network requests, and DOM operations will not be executed, but the running tasks will be executed. The browser may allow pages in the Frozen phase to periodically recover for a short period of time, and then briefly change back to the Hidden state, allowing a small number of tasks to be executed.

(6) Discarded stage

If the webpage is in the Frozen phase for a long time and the user does not wake up the page, it will enter the Discarded phase, that is, the browser automatically unloads the webpage and clears the memory usage of the webpage. However, if the webpages in the Passive phase have not been interacted for a long time, they may enter the Discarded phase directly.

This is generally enforced by the system without the user's intervention. Any type of new tasks or JavaScript code cannot be executed at this stage, because it is usually under resource constraints.

After the webpage is automatically Discarded by the browser, its Tab window is still there. If the user revisits the Tab page, the browser will re-issue a request to the server, reload the web page again, and return to the Active phase.

Common scenarios

The following are the life cycle changes of a few common scenarios.

(1) After the user opens the webpage, he switches to another App, but only returns to the webpage after a while.

The webpage changes from Active to Hidden, and then back to Active.

(2) After the user opens the webpage, he switches to another App and uses the latter for a long time, which causes the system to automatically discard the webpage.

The webpage changes from Active to Hidden, then to Frozen, and finally Discarded.

(3) After the user opens the web page, he switches to another App, and then clears the browser process from the task manager.

The webpage changes from Active to Hidden, and then Terminated.

(4) After the system discards the page in a tab, the user reopens the tab.

The webpage changes from Discarded to Active.

Incident

Each stage of the life cycle has its own events for developers to specify listening functions. Of these events, only two are newly defined (freeze event and resume event), the others are all existing.

Note that the life cycle events of a web page are triggered in all frames, whether it is the underlying frame or the embedded frame. That is to say, the embedded <iframe> webpage is the same as the top-level webpage, and will simultaneously listen to the following events.

focus event

The focus event is triggered when the page gets the input focus, for example, the page changes from the Passive stage to the Active stage.

blur event

The blur event is triggered when the page loses input focus, for example, the page changes from the Active phase to the Passive phase.

visibilitychange event

The visibilitychange event is triggered when the visible state of a webpage changes, and it usually occurs in the following scenarios.

  • The user hides the page (switches Tab, minimizes the browser), and the page changes from the Active stage to the Hidden stage.
  • The user revisits the hidden page, and the page changes from the Hidden stage to the Active stage.
  • When the user closes the page, the page will first enter the Hidden phase, and then enter the Terminated phase.

The callback function of this event can be specified through the document.onvisibilitychange property.

freeze event

The freeze event is triggered when the webpage enters the Frozen phase.

The callback function to be called when entering the Frozen phase can be specified through the document.onfreeze property.

function handleFreeze(e) {
  // Handle transition to FROZEN
}
document.addEventListener('freeze', handleFreeze);

# Or
document.onfreeze = function() {…}

The listener function for this event can only run for 500 milliseconds at the longest. And it can only reuse the network connection that has been opened, and cannot initiate a new network request.

Note that when entering the Discarded phase from the Frozen phase, no event will be triggered, and the callback function cannot be specified. You can only specify the callback function when entering the Frozen phase.

resume event

The resume event is triggered when the webpage leaves the Frozen phase and changes to the Active / Passive / Hidden phase.

The document.onresume property refers to the callback function that is called when the page leaves the Frozen phase and enters the available state.

function handleResume(e) {
  // handle state transition FROZEN -> ACTIVE
}
document.addEventListener("resume", handleResume);

# Or
document.onresume = function() {…}

pageshow event

The pageshow event is triggered when the user loads a web page. At this time, it may be a new page load, or it may be a page obtained from the cache. If it is obtained from the cache, the event.persisted property of the event object is true, otherwise it is false.

The name of this event is a bit misleading. It has nothing to do with the visibility of the page, only the change in the history record of the browser.

pagehide event

The pagehide event is triggered when the user leaves the current webpage and enters another webpage. Its premise is that the history record of the browser must change, and it has nothing to do with whether the web page is visible.

If the browser can add the current page to the cache for later reuse, the event.persisted property of the event object is true. If it is true. If the page is added to the cache, the page enters the Frozen state, otherwise it enters the Terminatied state.

beforeunload event

The beforeunload event is triggered when the window or document is about to be unloaded. When this event occurs, the document is still visible, and the uninstallation can still be cancelled at this time. After this event, the web page enters the Terminated state.

unload event

The unload event is triggered when the page is unloading. After this event, the web page enters the Terminated state.

Get the current stage

If the webpage is in Active, Passive or Hidden phase, you can get the current state of the webpage through the following code.

const getState = () => {
  if (document.visibilityState === "hidden") {
    return "hidden";
  }
  if (document.hasFocus()) {
    return "active";
  }
  return "passive";
};

If the webpage is in the Frozen and Terminated states, the timer code will not be executed, so the state can only be judged through event monitoring. Enter the Frozen phase, you can listen to the freeze event; enter the Terminated phase, you can listen to the pagehide event.

document.wasDiscarded

If a tab is in the Frozen phase, it may be discarded by the system at any time and enter the Discarded phase. If the user clicks the tab again later, the browser will reload the page.

At this time, the developer can determine whether the previous web page has been discarded by judging the document.wasDiscarded property.

if (document.wasDiscarded) {
  // The webpage is no longer in its original state, it has been discarded by the browser
  // restore the previous state
  getPersistedState(self.discardedClientId);
}

At the same time, two properties of window.clientId and window.discardedClientId will be added to the window object to restore the state before discarding.