Page Lifecycle API

Page Lifecycle API

Android, iOS and the latest Windows systems can automatically stop background processes at any time and release system resources in time. That is, 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 no way for developers to listen to the system discarding the page.

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

With this API, developers can predict the next state of the web page, so as to carry out various targeted processing. Chrome 68 supports this API, and for older browsers you can use the Google-developed compatibility library PageLifecycle.js.

Lifecycle stages

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

(1) Active Stage

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

(2) Passive Stage

In the Passive phase, the web page is visible, but has no input focus and cannot accept input. UI updates (like animations) are still being performed. This stage is only possible when the desktop has multiple windows at the same time.

(3) Hidden Stage

In the Hidden phase, the user’s desktop is occupied by other windows and the web page is not visible, but not yet frozen. UI updates are no longer performed.

(4) Terminated stage

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

This phase causes the webpage to be unloaded, any new tasks will not be started during this phase, and ongoing tasks may be killed if they run for too long.

(5) Frozen Stage

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

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

(6) Discarded Stage

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

This is generally enforced by the system without user intervention. New tasks or JavaScript code of any kind cannot be executed at this stage, as this is usually a resource-constrained situation.

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

Common scenarios

The following are page life cycle changes for several common scenarios.

(1) After the user opens the web page, he switches to another app, but only returns to the web page after a while.

The web page changes from Active to Hidden and back to Active.

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

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

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

The web page becomes Hidden from Active, and then Terminated.

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

The webpage changes from Discarded to Active.

event

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

Note that the lifecycle events of the web page are triggered on all frames, whether it is the underlying frame or the embedded frame. That is to say, the embedded <iframe> web page will listen to the following events at the same time as the top-level web page.

focus event

The focus event is fired when the page gains input focus, such as when the page changes from the Passive stage to the Active stage.

blur event

The blur event is fired when the page loses input focus, such as when the page changes from Active to Passive.

visibilitychange event

The visibilitychange event is triggered when the visibility state of the web page changes, which generally 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 stage, and then enter the Terminated stage.

A callback function for this event can be specified via the document.onvisibilitychange property.

freeze event

The freeze event is fired when the page enters the Frozen phase.

A callback function to be called when entering the Frozen phase can be specified via 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 a maximum of 500 milliseconds. 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 stage from the Frozen stage, no event will be triggered, and the callback function cannot be specified. The callback function can only be specified when entering the Frozen stage.

resume event

The resume event is fired when the page leaves the Frozen stage and becomes the Active / Passive / Hidden stage.

The document.onresume property refers to the callback function called when the page leaves the Frozen stage 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 fires when the user loads the page. At this point, it may be a fresh page load, or it may be a page fetched from the cache. The event object’s event.persisted property is true if fetched from the cache, false otherwise.

The name of this event is a bit misleading, it has nothing to do with the visibility of the page, only changes to the browser’s History record.

pagehide event

The pagehide event is fired when the user leaves the current page and enters another page. Its premise is that the browser’s History record must change, regardless of whether the web page is visible or not.

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

beforeunload event

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

unload event

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

Get the current stage

If the web page is in Active, Passive or Hidden stage, the current state of the web page can be obtained through the following code.

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

If the web page is in the Frozen and Terminated states, since the timer code will not be executed, the state can only be judged through event monitoring. In the Frozen stage, you can listen to the freeze event; in the Terminated stage, you can listen to the pagehide event.

document.wasDiscarded

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

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

if (document.wasDiscarded) {
  // The page is no longer in its original state and was once discarded by the browser
  // restore previous state
  getPersistedState(self.discardedClientId);
}

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

Reference link