GithubHelp home page GithubHelp logo

bhanditz / network-idle-callback Goto Github PK

View Code? Open in Web Editor NEW

This project forked from pastelsky/network-idle-callback

1.0 2.0 0.0 3.19 MB

Like requestIdleCallback, but for detecting network idle

Home Page: https://pastelsky.github.io/network-idle-callback

License: MIT License

HTML 10.90% JavaScript 46.15% CSS 42.95%

network-idle-callback's Introduction

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.

network-idle-callback's People

Contributors

pastelsky avatar bendrucker avatar

Stargazers

Rhony avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.