network-idle-callback

2.0.1 • Public • Published

networkIdleCallback

networkIdleCallback works similar to requestIdleCallback, detecting and notifying you when network activity goes idle in your current tab.

It can be used to load low priority resources such as analytics, or for preloading assets required in the future.

DEMO

Installation

npm install network-idle-callback

Usage

Setup

networkIdleCallback uses a serviceworker to detect network activity. The easiest way to begin monitoring network activity is by importing the script into your serviceworker, and wrapping your fetch calls as such -

// via CDN
importScripts('https://unpkg.com/network-idle-callback@1.0.1/lib/request-monitor.js')
 
// or if you process your sw through a bundler
import 'network-idle-callback/lib/request-monitor'
 
self.addEventListener('fetch', function (event) {
  self.requestMonitor.listen(event) // Listen to outgoing network requests
 
  const fetchPromise = fetch(event.request)
    .then((response) => {
      self.requestMonitor.unlisten(event) // Unlisten to successful requests
      return response
    })
    .catch((e) => {
      self.requestMonitor.unlisten(event) // Unlisten to failed requests
    })
 
  event.respondWith(fetchPromise)
});

and that's it. You're good to start using the callback -

import { networkIdleCallback } from 'network-idle-callback'
 
networkIdleCallback(() => {
  console.log('Execute low network priority tasks here.')
}, { timeout: 1000 })

The callback will be passed a params object containing -

  1. didTimeout (boolean) - Indicates whether the callback was called due to expiration of the deadline.

Changing timeouts

There are a couple of ways in which the networkIdleCallback can be customized -

  1. Idle Deadline : (default 0ms) It is recommended to specify a deadline — the maximum time to wait for network idle, after the expiry of which the callback will be executed regardless of network activity.
networkIdleCallback(() => {
  console.log('Execute low network priority tasks here.')
}, { timeout: 1000 /* here */ })
  1. Network activity cooldown - By default, networkIdleCallback waits for a period of 200ms after network activity ceases to trigger the callbacks. If you want to reduce this debounce time, in your serviceworker, you can set -
self.requestMonitor.minIdleTime = 0 // or any other value

Cancelling a callback

Just like requestIdleCallback, calling networkIdleCallback returns a unique identifier, which can be used to cancel the execution of the callback -

import { networkIdleCallback, cancelNetworkCallback } from 'network-idle-callback'
 
const id = networkIdleCallback(() => {
  console.log('Execute low network priority tasks here.')
}, { timeout: 1000 })
 
// Cancel the callback
cancelNetworkCallback(id)

Browser compatibility

networkIdleCallback should work in all browsers that support serviceworkers. For browsers that don't, the callback will be still be called, but immediately, without any delay.

FAQ's

1. Why not just use the window.onload instead ?

  • window.onload also waits for all of the page's rendering is complete. If the rendering work is expensive and takes a long time, there could be a time difference between when the resources have finished loading (network idle) and when window.load fires.

  • A larger limitation, perhaps, is that it fires only once during the lifecycle of the page. Hence it cannot be used to detect network idle states occurring after page load. This can especially be of use for preloading content in single page applications.

2. When exactly does the networkIdleCallback execute ?

Lifecycle

3. Does networkIdleCallback take into account network activity arising from other clients?

Since a serviceworker can only listen to network activity arising from the domains it was registered with, without the support of a browser primitive, there is currently no way to detect network activity from other domains, or apps other than your web browser.

However, more often than not, this is the behavior you expect, as you're only concerned with prioritizing resource loading in the context of the current tab.

4. What happens if my serviworker is installed, but not activated?

In the absence of a activated service worker, the callbacks will be executed immediately. If you can, calling skipWaiting() in the activation phase will skip the activation delay.

Readme

Keywords

none

Package Sidebar

Install

npm i network-idle-callback

Weekly Downloads

87

Version

2.0.1

License

MIT

Unpacked Size

11.1 kB

Total Files

8

Last publish

Collaborators

  • pastelsky