Why does the Web need LifeCycle API?

There was no previous concept of a life cycle on the Web, and applications could remain alive indefinitely.

But in order to save resources, browsers need to take aggressive steps to save resources on background TAB pages, but developers are currently not prepared for these types of system launch interventions, and browsers need to be conservative or risk damaging pages.

The browser’s judgment is often inaccurate, and a page lifecycle API was introduced to address this problem.

What does the LifeCycle API include?

  • Introduce the concept of a standardized lifecycle
  • Defines a new system startup state that allows the browser to restrict the resources available to hidden or inactive tabs
  • Create new apis and events that allow Web developers to respond to transitions to these new system startup states

Chrome 68 introduced

Phase is introduced

The life cycle of a web page is divided into six phases:

Active

Web pages handle visible state and have input focus

Passive

Page visible, no input focus, cannot accept input. UI updates (such as animations) are still being performed. This can only happen if the desktop has multiple Windows at the same time

Hidden

The page is not visible but has not been frozen. UI updates are no longer performed

Terminated

The current page starts to be unmounted by the browser and erased from memory because the user actively closes the window or travels to another page in the same window.

  • This phase is always inHiddenPhases occur after, that is, the user actively leaves the current page and always enters firstHiddenPhase, then go inTerminatedphase
  • This node causes the web page to unload, no new tasks are started at this stage, and ongoing tasks may be terminated if running time is too long

Frozen

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

In this phase, the web page is no longer allocated CPU computing resources. Timers, callbacks, network requests, and DOM operations will not execute, but running tasks will finish. The browser may allow pages in the Frozen phase to periodically revive for a short time, return to Hidden for a short time, and allow a small number of tasks to execute

Discarded

If a web page is Discarded for a long time and a user does not wake up the Frozen page, the web page enters the Discarded stage. If a web page is Discarded for a long time, the browser automatically disinstalls the web page to clear its memory usage. However, if a page in the Passive phase does not interact for a long time, it may enter the discarding phase

Generally, the system forces the execution without user intervention. No new tasks or JS code of any kind can be executed at this stage because it is usually under resource constraints.

After a web page has been automatically Discarded by the browser, its Tab window remains open. If the user returns to the Tab page, the browser will re-request the server to reload the page again, returning to the Active phase

Events that

Lifecycle events are emitted on all frames. The embedded <iframe> page listens for the following events at the same time as the top-level page.

  • Event handlers to add towindowobject
  • visibilitychangeCan be found indocumentListening;
  • freeze/resumeOnly in thedocumentOn the monitor

Focus:

  • Triggered when the page gets input focus
  • Such asPassive -> Active

blur:

  • Triggered when the page loses input focus
  • Such asActive -> Passive
  • Event handlers to add towindowobject

visibilitychange:

Triggered when the web page’s visible status changes

  • Use CSS to make

Such as:

  • Hide pages (toggle tabs, minimize browser, etc.)Active -> Hidden
  • The user returns to the hidden page,Hidden -> Active
  • The user closes the page,Hidden -> Terminated

Document. visibilityState When the read-only property changes, the window state is:

  • “Visible” :
    • Page content is at least partially visible. Means that the page is the foreground TAB of a non-minimized window
  • “Hidden” :
    • Part of the background TAB | minimize window | OS screen lock
  • “Prerender”
    • Page content is being prerendered and not visible to the user (document.hidden as hidden).
    • The document might start in this state, but not by other value conversions
    • Browsers may not support it

  • ‘unloaded’
    • The page is being unloaded from memory
    • Browsers may not support it

Document. hidden Read-only property:

  • True: the page is hidden from the user
  • False: other
  • Reserved for historical reasons, use as much as possibledocument.visibilityStateattribute

Freeze (new definition)

  • Enter the pageFrozenStage time trigger
  • Can be achieved bydocument.onfreezeProperty specifies entryFrozenThe callback function that is invoked when the
  • This function listens for events that run up to 500ms. In addition, you can reuse only existing network connections and cannot initiate new network requests
  • FrozenDiscardedThe phase does not trigger any events and cannot specify callback functions, only on entryFrozenPhase specifies the callback function

Resume (new definition)

  • resumeThe event leaves on the pageFrozenStage, intoActive/Passive/HiddenStage time trigger
  • document.onresumeIt means the page goes awayFrozenPhase, the callback function that is called when the state is available

Pageshow:

  • Triggered when the user loads a web page. This could be a brand new page loading or a page fetched from the cache. Of the event object if retrieved from the cacheevent.persistedProperty is true, otherwise false

The misleading name has nothing to do with page visibility, and everything to do with changes in the browser’s History

Pagehide:

Triggered when the user leaves the current page and goes to another page. The premise is that the browser’s History must change, regardless of whether the 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 the page is added to the cache, the page enters the Frozen state; otherwise, the page enters the Terminatied state

Beforeunload events

  • Triggered when a window or document is about to unload. The document is still visible when this event occurs, and uninstallation can still be cancelled. After this event, the page entersTerminatedstate
  • similarunloadThe problem. It is recommended to listen only when the user has unsaved changes and delete them immediately after saving them

The unload event

  • Triggered while the page is being unloaded. After this event, the page entersTerminatedstate
  • Avoid it in modern browsers, especially on mobile devices
  • Best rely onvisibilitychangeEvent to determine when the session ends and willhiddenState is the last reliable time to save application and user data
  • It is recommended to usepagehideEvent to detect possible page unloads (terminatedState)

Different events need to be tied to different objects to trigger. Visibilitychange events can be triggered on the window/document, pagehide/pageshow/blur/focus only on the window trigger, freeze and resume can be triggered in the document. The reason remains to be proved www.w3.org/TR/html/ful…

How to get the current stage:

API

The status of the Active/Passive/Hidden phase can be obtained with the following code:

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

Event listeners

Frozen and Terminated state. The timer code is not executed and can only be tested by event listening.

  • Freeze: Enter the Frozen
  • Pagehide: Terminated

Document. WasDiscarded (Chrome 68)

If a TAB is Frozen, the system may discard it at any time. If the user clicks the TAB again, the browser reloads the page

At this point, the developer can determine if the previous web page wasDiscarded by identifying the document.wasDiscarded attribute

The window.clientId and window.discardedClientId properties will be added to the window object to restore the state before discarding

Cross-browser differences

  • The new event and DOM apis are not yet implemented in all browsers

  • The events now implemented in browsers are also inconsistent:

  • Compatible library: pagelifecyre.js

Some UAs have restrictions on background or hidden tabs:

Most browsers stop sending requestAnimationFrame() callbacks to hidden tabs or hidden

For example, setTimeout() is restricted in the background/inactive TAB, see Reasons for Delays longer than Specified

Modern browsers (Firefox 58+, Chrome 57+) use budget-based background timeout limits to set additional limits on background CPU usage.

  • In Firefox, Windows in the background TAB have their own time budget (in milliseconds), with a maximum of +50ms and a minimum of -150ms.

Chrome is very similar, except that the budget is specified in seconds

  • Windows is limited after 30s and has the same limited delay rules as window calculators. In Chrome, the value is 10s
  • Timer tasks are allowed only if the budget is non-negative
  • Once the timer code has finished running, subtract the duration of execution from its window’s timeout budget
  • In Firefox and Chrome, budgets are regenerated at a rate of 10ms per second

Some processes may be exempt from this restrictive behavior. In this case, the Page Visibility API can be used to reduce the performance impact of tags when they are hidden

  • The TAB that plays audio is treated as foreground and not affected
  • Unrestricted tabs for code running real-time network connections (WebSockets and WebRTC) to avoid closing these connections by timeout and accidental closure
  • IndexDB processes are not restricted to avoid timeouts

Chrome ://discards/ can see page state and control

Compatible library PageLifecycle. Js

PageLifecycle. Js implementation:

getCurrentState()

  • Returns: the active | passive | hidden
  • Judge by document visibility and hasFocus(). Other states need to be retrieved using getState(), which listens for events

GetState () :

  • EVENTS:
    • Internet Explorer 9-10 does not support pageHide and uses Unload instead
    • Safari does not reliably trigger Pagehide or Visibilitychange when closing a TAB, so use beforeUnload and timeout timing to check if the default action is blocked

Reference:

Standard: wicg. Making. IO/page – lifecy…

Docs.google.com/document/d/…

Chrome API: developers.google.com/web/updates…

Nguyen other tutorial: www.ruanyifeng.com/blog/2018/1…

Google Compatible library pagelifecyre.js: github.com/GoogleChrom…