Visibility.js

2.0.2 · active · verified Tue Apr 21

Visibility.js is a lightweight JavaScript library providing a robust wrapper around the native Page Visibility API, abstracting away vendor prefixes and offering enhanced utility functions. The current stable version is 2.0.2, with recent updates focusing on modernizing its distribution (removing support for legacy package managers in 2.0.0) and improving TypeScript definitions. Its core strength lies in intelligent timers and event handlers: `Visibility.every` creates timers that automatically pause or adjust intervals when a page is hidden, optimizing resource usage, while `onVisible` and `onHidden` provide direct callbacks for state changes. A key differentiator is its built-in fallback for older browsers, although this feature has a known limitation when a browser window loses focus but remains visible.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `Visibility.every` for interval-based tasks, `Visibility.stop` to clear timers, and `Visibility.onVisible`/`onHidden` for reacting to page visibility state changes.

import Visibility from 'visibilityjs';

// Example 1: Update a countdown every second only when the page is visible
const countdownTimerId = Visibility.every(1000, () => {
  console.log('Page is visible! Updating countdown...');
  // In a real app, you would update a UI element here
});

// Example 2: Check for emails every minute when visible, every 5 minutes when hidden
const emailCheckTimerId = Visibility.every(60 * 1000, 5 * 60 * 1000, () => {
  console.log('Checking for new emails...');
  // Make an AJAX request or similar
});

// Stop a timer after 10 seconds for demonstration
setTimeout(() => {
  Visibility.stop(countdownTimerId);
  console.log('Countdown timer stopped.');
}, 10000);

// Example 3: Perform an action when the page becomes visible
Visibility.onVisible(() => {
  console.log('Welcome back! Page is now visible.');
  // Resume video playback or animations
});

// Example 4: Perform an action when the page becomes hidden
Visibility.onHidden(() => {
  console.log('Page is now hidden. Pausing heavy tasks.');
  // Pause video, stop heavy animations, etc.
});

view raw JSON →