JavaScript - Events

Page Lifecycle API

Application lifecycle is a key way that modern operating systems manage resources. On Android, iOS, and recent Windows versions, apps can be started and stopped at any time by the OS. This allows these platforms to streamline and reallocate resources where they best benefit the user.

On the web, there has historically been no such lifecycle, and apps can be kept alive indefinitely. With large numbers of web pages running, critical system resources such as memory, CPU, battery, and network can be oversubscribed, leading to a bad end-user experience.

While the web platform has long had events that related to lifecycle states — like load, unload, and visibilitychange — these events only allow developers to respond to user-initiated lifecycle state changes. For the web to work reliably on low-powered devices (and be more resource conscious in general on all platforms) browsers need a way to proactively reclaim and re-allocate system resources.

In fact, browsers today already do take active measures to conserve resources for pages in background tabs, and many browsers (especially Chrome) would like to do a lot more of this — to lessen their overall resource footprint.

The problem is developers currently have no way to prepare for these types of system-initiated interventions or even know that they’re happening. This means browsers need to be conservative or risk breaking web pages.

The Page Lifecycle API attempts to solve this problem by:

  • Introducing and standardizing the concept of lifecycle states on the web.
  • Defining new, system-initiated states that allow browsers to limit the resources that can be consumed by hidden or inactive tabs.
  • Creating new APIs and events that allow web developers to respond to transitions to and from these new system-initiated states.

This solution provides the predictability web developers need to build applications resilient to system interventions, and it allows browsers to more aggressively optimize system resources, ultimately benefiting all web users.

Allow Ctrl- and Shift-clicking links in event handlers

I just recently updated a bunch of my click handlers to not act when the Ctrl or Shift keys are pressed during the click, so that links can be opened in new tabs or windows by the user if so wanted:

Code language: JavaScript

// Don't do anything and defer to the default action if a modifier key
// was pressed during the click (to open the link in a new tab, window,
// etc.) - note that this is a truthy check rather than a strict check
// for the existence of and boolean true value of the various event
// properties:
// * https://ambientimpact.com/web/snippets/conditional-statements-and-truthy-values-robust-client-side-javascript
// * https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/ctrlKey
// * https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/shiftKey
if (event.ctrlKey || event.shiftKey) {
  return;
}

An event for CSS position: sticky

Here’s a secret: You may not need scroll events in your next app. Using an IntersectionObserver, I show how you can fire a custom event when position:sticky elements become fixed or when they stop sticking. All without the use of scroll listeners.

[…]

One of the practical limitations of using CSS sticky position is that it doesn’t provide a platform signal to know when the property is active. In other words, there’s no event to know when an element becomes sticky or when it stops being sticky.

Async events in ServiceWorkers with "event.waitUntil"

It’s asynchronous, see? So even though all that network code appears before the return statement, it’s pretty much guaranteed to complete after the cache response has been returned. You can verify this by putting in some console.log statements:

Code language: JavaScript

caches.match(request)
.then( responseFromCache => {
  if (responseFromCache) {
      event.waitUntil(
          fetch(request)
          .then( responseFromFetch => {
              console.log('Got a response from the network.');
              caches.open(staticCacheName)
              .then( cache => {
                  cache.put(request, responseFromFetch);
              });
          })
      );
      console.log('Got a response from the cache.');
      return responseFromCache;
  }

Those log statements will appear in this order:

Got a response from the cache.
Got a response from the network.

That’s the opposite order in which they appear in the code. Everything inside the event.waitUntil part is asynchronous.

Here’s the catch: this kind of asynchronous waitUntil hasn’t landed in all the browsers yet. The code I’ve written will fail.

But never fear! Jake has written a polyfill. All I need to do is include that at the start of my serviceworker.js file and I’m good to go:

Code language: JavaScript

// Import Jake's polyfill for async waitUntil
importScripts('/js/async-waituntil.js');