All Projects → pastelsky → Network Idle Callback

pastelsky / Network Idle Callback

Licence: mit
Like requestIdleCallback, but for detecting network idle

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Network Idle Callback

Cisco ios
Ansible Network Cisco IOS Provider Role
Stars: ✭ 72 (-14.29%)
Mutual labels:  network
Ansible For Network Engineers
Репозиторий книги "Ansible для сетевых инженеров". Книга в процессе переноса на readthedocs и обновления содержания на Ansible 2.9!
Stars: ✭ 74 (-11.9%)
Mutual labels:  network
Homebox
A Toolbox for Home Local Networks
Stars: ✭ 78 (-7.14%)
Mutual labels:  network
Vbox
vue实现的音乐Web App
Stars: ✭ 73 (-13.1%)
Mutual labels:  service-worker
Smart Buffer
smart-buffer is a Buffer wrapper that adds automatic read & write offset tracking, string operations, data insertions, and more.
Stars: ✭ 73 (-13.1%)
Mutual labels:  network
Vpnify
vpnify - transparently route traffic of a process through VPN
Stars: ✭ 74 (-11.9%)
Mutual labels:  network
Serial Studio
Multi-purpose serial data visualization & processing program
Stars: ✭ 1,168 (+1290.48%)
Mutual labels:  network
Http2dotnet
HTTP/2 support for .NET standard
Stars: ✭ 80 (-4.76%)
Mutual labels:  network
I2p.i2p
I2P is an anonymizing network, offering a simple layer that identity-sensitive applications can use to securely communicate. All data is wrapped with several layers of encryption, and the network is both distributed and dynamic, with no trusted parties.
Stars: ✭ 1,186 (+1311.9%)
Mutual labels:  network
Thor Os
Simple operating system in C++, written from scratch
Stars: ✭ 1,204 (+1333.33%)
Mutual labels:  network
Pynms
A vendor-agnostic NMS for carrier-grade network simulation and automation
Stars: ✭ 73 (-13.1%)
Mutual labels:  network
Dna
Discourse Network Analyzer (DNA)
Stars: ✭ 73 (-13.1%)
Mutual labels:  network
2016lykagguvenligivesizmatestleri
Network Security Notes ☔️
Stars: ✭ 75 (-10.71%)
Mutual labels:  network
Tinybirdnet Unity
A high level API for making networked games in Unity, utilizes https://github.com/RevenantX/LiteNetLib
Stars: ✭ 72 (-14.29%)
Mutual labels:  network
Nac bypass
Script collection to bypass Network Access Control (NAC, 802.1x)
Stars: ✭ 79 (-5.95%)
Mutual labels:  network
Service Worker Router
➰ An elegant and fast URL router for service workers (and standalone use)
Stars: ✭ 70 (-16.67%)
Mutual labels:  service-worker
Jsprintmanager
Advanced Client-side Printing & Scanning Solution for Javascript
Stars: ✭ 74 (-11.9%)
Mutual labels:  network
Grapher
✍️ Large interactive graphs
Stars: ✭ 84 (+0%)
Mutual labels:  network
Go2p
Simple to use but full configurable p2p framework
Stars: ✭ 80 (-4.76%)
Mutual labels:  network
Cifsd
cifsd kernel server(SMB/CIFS server)
Stars: ✭ 76 (-9.52%)
Mutual labels:  network

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].