• Stars
    star
    135
  • Rank 260,494 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Like requestIdleCallback, but for detecting network idle

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/[email protected]/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.

More Repositories

1

bundlephobia

๐Ÿ‹๏ธ Find out the cost of adding a new frontend dependency to your project
JavaScript
8,606
star
2

tsdocs

Browse type documentation for JS libraries
TypeScript
1,034
star
3

package-build-stats

This is the cloud function that powers the core of building, minifying and gzipping of packages in bundlephobia
JavaScript
91
star
4

covid-19-mobility-tracker

Google Mobility Reports, reverse-engineered into a JSON / CSV API
JavaScript
85
star
5

useragent-generator

Easily generate correct user-agent strings for popular browsers
JavaScript
66
star
6

curldiff

An interactive utility to compare differences between two curl requests in a human readable format
JavaScript
14
star
7

similar-npm-packages

Similar packages suggestions for the NPM ecosystem
TypeScript
8
star
8

google-analytics-logger-extension

Check if your Google analytics events are firing as they should using this convenient open-source logger.
JavaScript
7
star
9

mobx-promise

A tiny dependency-free library that makes working with promises in MobX easy.
JavaScript
6
star
10

throttle-queue

A promise based priority queue with task deduplication, concurrency control, serial resolution and aging
JavaScript
6
star
11

nnc

Visualisation for nearest neighbour chain algorithm
JavaScript
5
star
12

sort-class-members-codemod

A codemod for automatically fixing issues reported by eslint-plugin-sort-class-members
JavaScript
4
star
13

a-b-experiments

A presentation about the ABCs of A/B Experiments
JavaScript
3
star
14

developing-interactions

A presentation on developing delightful micro interactions on the web
JavaScript
2
star
15

ttc

Measure the time taken to compelete a flow from home page to the cart page.
JavaScript
2
star
16

parse-http-header

Parse values of request as well as response HTTP headers
JavaScript
2
star
17

awesome-ab-experiments

A curated list of resources about running A/B tests
2
star
18

a-k-apart

CSS
1
star
19

ud_portfolio

Level 0 App for Android Nanodegree which showcases portfolio of apps built in this excercise
Java
1
star
20

es6-webpack-presentation

ES6, Babel and Webpack
HTML
1
star
21

carpediem-archive

Archived website for the 2016 edition of IIMC's Carpe Diem fest
HTML
1
star
22

semver-closest

Find the closest matching semver from an array of semver versions
JavaScript
1
star
23

ccn

1
star
24

cloud9

HTML
1
star
25

kaldi-hugo-cms-template

CSS
1
star
26

merge-conflicts

HTML
1
star
27

renovate-range-strategy-repro

1
star
28

gatsby-starter-netlify-cms

JavaScript
1
star
29

RoadRunner

FYP
HTML
1
star
30

todos-test

JavaScript
1
star
31

MAD-Notes

1
star
32

playwright-bug-context-close

TypeScript
1
star
33

dust-loader-complete

A complete webpack loader for DustJS files.
JavaScript
1
star
34

marginauto

A blog about design and front end tips and tricks.
CSS
1
star
35

bitbucket-api-client

JavaScript
1
star
36

UD-MoviesApp

MOvies app P1 for udacity android nanodegree.
Java
1
star
37

bookmybook

HTML
1
star
38

Utsav_2015_new

Java
1
star