npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

network-idle-callback

v2.0.1

Published

<img src="https://img.shields.io/npm/v/network-idle-callback.svg" /> <img src="https://img.shields.io/npm/l/network-idle-callback.svg" />

Downloads

36

Readme

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 ?

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.