Browser API Every Frontend Developer Should Know
As users, we always like to multi-task while browsing web pages. So it’s common to have several browser tabs open as it helps to get things done in parallel. However, at the same time, each of these tabs consumes system resources like memory and CPU.
Since it’s impossible to limit users from opening new browser tabs and leaving them behind, browsers have taken several measures to deallocate resources when the browser tabs aren’t active.
Modern browsers today will sometimes suspend pages or discard them entirely when system resources are constrained — Philip Walton
So you might wonder why we need to worry about this, as it is taken care of by the browser?
However, if you happen to choose between these two, it’s worth mentioning some of the limitations of the Page Visibility API.
- It only provides visible and hidden states of a web page.
- It can not capture pages discarded by the operating system (Android, IOS, and the latest Windows systems can terminated background processes to preserve system resources).
Let’s take a look at the page lifecycle states exposed by the Page Lifecycle API.
There are six states introduced in the API. Out of them, two states are quite relevant to us.
- FROZEN — Lifecycle state for CPU suspension (Hidden pages will be frozen to conserve resources).
If a webpage has been hidden for a long time and the user does not close the page, the browser will freeze it and move the page into this state. However, the running tasks will continue until completed. But timers, callback function executions, and DOM operations will be stopped to release the CPU.
When I look at the Chrome Browser resource consumption on my PC, I observed that the two active tabs consume 14.7% and 11% of the CPU while the Frozen ones consume nearly 0%.
- DISCARDED — Frozen frames are moved to the Discarded state to conserve resources.
Suppose a webpage is in a frozen state for a long time. In that case, the browser will automatically unload the page into the discarded state, releasing some memory. And If the user re-visits a discarded page, the browser will reload the page to return to the Active State.
It’s worth noticing that the users will typically experience the discarded state in devices with resource constraints.
Apart from the above two states, there are four other states introduced in the API as,
- ACTIVE — Page is visible and has input focus.
- PASSIVE — Page is visible but doesn’t have input focus.
- HIDDEN — Page is not visible (Not frozen either).
- TERMINATED — Page is unloaded and cleared from memory.
You can find the lifecycle states and the transition in detail by looking at the following diagram.