• Stars
    star
    1,825
  • Rank 25,437 (Top 0.6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 13 years ago
  • Updated 10 months ago

Reviews

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

Repository Details

Wrapper for the Page Visibility API

Visibility.js Build Status

Visibility.js is a wrapper for the Page Visibility API. It hides vendor prefixes and adds high level functions.

Page Visibility API allows you to determine whether your web page is either visible to a user or hidden in background tab or prerendering. It allows you to use the page visibility state in JavaScript logic and improve browser performance by disabling unnecessary timers and AJAX requests, or improve user interface experience (for example, by stopping video playback or slideshow when user switches to another browser tab).

Moreover, you can detect if the browser is just prerendering the page while the user has still not opened the link, and don’t count this as a visit in your analytics module, or do not run heavy calculations or other actions which will disable the prerendering.

Page Visibility API is natively supported by all browsers. For old browsers you can use lib/visibility.fallback.js with focus/blur hack (note that this hack has an issue: when browser just lose focus but still visible for user, its state will change to [hidden]).

Sponsored by Evil Martians

Translations

Документация на русском: habrahabr.ru/blogs/javascript/125833/

States

Currently the Page Visibility API supports three visibility states:

  • visible: user has opened the page and works within it.
  • hidden: user has switched to another tab or minimized browser window.
  • prerender: browser is just prerendering a page which may possibly be opened by the user to make the apparent loading time smaller.

Timers

The main use case for this library is to enable some of the times only when content is visible to the user, i.e. the ones animating a countdown animation.

Visibility.every(interval, callback) is similar to setInterval(callback, interval), but calls callback every interval ms only if the page is visible. For example, let’s create a countdown timer:

Visibility.every(1000, function () {
    updateCountdownAnimation();
});

You can provide an additional interval which will be used when the page is hidden. In next example, a check for inbox updates will be run every 1 minute for a visible page and every 5 minutes for a hidden one:

var minute = 60 * 1000;
Visibility.every(minute, 5 * minute, function () {
    checkForEmail();
});

When the page becomes visible, if the callback has not been called in longer than the visible interval, it will be called immediately. In the example above, if you hid the page for 9 minutes, checkForEmail will get called once while the page is hidden, and immediately when it is made visible.

Visibility.every returns a timer identifier, much like the setInterval function. However, it cannot be passed to clearInterval, and you should use Visibility.stop(id) to stop the timer.

var slideshow = Visibility.every(5 * 1000, function () {
    nextSlide();
});

$('.stopSlideshow').click(function () {
    Visibility.stop(slideshow);
});

If the browser does not support the Page Visibility API, Visibility.every will fall back to setInterval, and callback will be run every interval ms for both the hidden and visible pages.

Initializers

Another common use case is when you need to execute some actions upon a switch to particular visibility state.

Waiting until the page becomes visible

Visibility.onVisible(callback) checks current state of the page. If it is visible now, it will run callback, otherwise it will wait until state changes to visible, and then run callback.

For example, let’s show an animated notification only when the page is visible, so if some user opens a page in the background, the animation will delay until the page becomes visible, i.e. until the user has switched to a tab with the page:

Visibility.onVisible(function () {
    startIntroAnimation();
});

If a browser doesn’t support Page Visibility API, Visibility.onVisible will run the callback immediately.

Wait until the page is opened after prerendering

A web developer can hint a browser (using Prerendering API) that an user is likely to click on some link (i.e. on a “Next” link in a multi-page article), and the browser then may prefetch and prerender the page, so that the user will not wait after actually going via the link.

But you may not want to count the browser prerendering a page as a visitor in your analytics system. Moreover, the browser will disable prerendering if you will try to do heavy computations or use audio/video tags on the page. So, you may decide to not run parts of the code while prerendering and wait until the user actually opens the link.

You can use Visibility.afterPrerendering(callback) in this cases. For example, this code will only take real visitors (and not page prerenderings) into account:

Visibility.afterPrerendering(function () {
    Statistics.countVisitor();
});

If the browser doesn’t support Page Visibility API, Visibility.afterPrerendering will run callback immediately.

Low-level API

In some cases you may need more low-level methods. For example, you may want to count the time user has viewed the page in foreground and time it has stayed in background.

Visibility.isSupported() will return true if browser supports the Page Visibility API:

if( Visibility.isSupported() ) {
    Statistics.startTrackingVisibility();
}

Visibility.state() will return a string with visibility state. More states can be added in the future, so for most cases a simpler Visibility.hidden() method can be used. It will return true if the page is hidden by any reason. For example, while prerendering, Visibility.state() will return "prerender", but Visibility.hidden() will return true.

This code will aid in collecting page visibility statistics:

$(document).load(function () {

    if ( 'hidden' == Visibility.state() ) {
        Statistics.userOpenPageInBackgroundTab();
    }
    if ( 'prerender' == Visibility.state() ) {
        Statistics.pageIsPrerendering();
    }

});

And this example will only enable auto-playing when the page is opening as a visible tab (not a background one):

$(document).load(function () {

   if ( !Visibility.hidden() ) {
       VideoPlayer.play();
   }

});

Using Visibility.change(callback) you can listen to visibility state changing events. The callback takes 2 arguments: an event object and a state name.

Let’s collect some statistics with this events approach:

Visibility.change(function (e, state) {
    Statistics.visibilityChange(state);
});

Method change returns listener ID. You can use it to unbind listener by Visibility.unbind(id):

var listener = Visibility.change(function (e, state) {
    if ( !Visibility.hidden() ) {
       VideoPlayer.pause();
    }
});

VideoPlayer.onFinish(function () {
    Visibility.unbind(listener);
});

Methods onVisible and afterPrerendering will also return listener ID, if they wait visibility state changes. If they execute callback immediately, they return true if Page Visibility API is supported and false if they can’t detect visibility state.

var listener = Visibility.onVisible(function () {
    notification.takeAttention();
});

notification.onOutOfDate(function () {
    if ( typeof(listener) == 'number' ) {
        Visibility.unbind(listener);
    }
});

Packages

Visibility.js is shipped with 4 files:

  • visibility.core – core module.
  • visibility.timersevery and stop methods to set setInterval depend on visibility state.
  • visibilityvisibility.core and visibility.timers together.
  • visibility.fallback – fallback for browser without Page Visibility API. It use document focus/blur events, so document become to be hidden, when browser just lose focus, but still visible for user.

Installing

Available by NPM:

npm install --save visibilityjs

Contributing

  1. To run tests you need node.js and npm. For example, in Ubuntu run:

    sudo apt-get install nodejs npm
  2. Next install npm dependencies:

    npm install
  3. Run all tests:

    npm test
  4. Also you can see real usage example in integration test test/integration.html.

More Repositories

1

nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript
JavaScript
24,064
star
2

easings.net

Easing Functions Cheat Sheet
CSS
7,908
star
3

size-limit

Calculate the real cost to run your JS app or lib to keep good performance. Show error in pull request if the cost exceeds the limit.
JavaScript
6,487
star
4

nanoevents

Simple and tiny (107 bytes) event emitter library for JavaScript
TypeScript
1,442
star
5

autoprefixer-rails

Autoprefixer for Ruby and Ruby on Rails
Ruby
1,213
star
6

nanocolors

Use picocolors instead. It is 3 times smaller and 50% faster.
JavaScript
868
star
7

audio-recorder-polyfill

MediaRecorder polyfill to record audio in Edge and Safari
JavaScript
580
star
8

keyux

JS library to improve keyboard UI of web apps
TypeScript
380
star
9

webp-in-css

PostCSS plugin and tiny JS script (131 bytes) to use WebP in CSS background
JavaScript
346
star
10

offscreen-canvas

Polyfill for OffscreenCanvas to move Three.js/WebGL/2D canvas to Web Worker
JavaScript
332
star
11

convert-layout

JS library to convert text from one keyboard layout to other
JavaScript
251
star
12

ssdeploy

Netlify replacement to deploy simple websites with better flexibility, speed and without vendor lock-in
JavaScript
194
star
13

environment

My home config, scripts and installation process
Shell
193
star
14

nanodelay

A tiny (37 bytes) Promise wrapper around setTimeout
JavaScript
189
star
15

dual-publish

Publish JS project as dual ES modules and CommonJS package to npm
JavaScript
186
star
16

nanospy

Spy and mock methods in tests with great TypeScript support
TypeScript
138
star
17

check-dts

Unit tests for TypeScript definitions in your JS open source library
JavaScript
138
star
18

autoprefixer-core

autoprefixer-core was depreacted, use autoprefixer
JavaScript
136
star
19

transition-events

jQuery plugin to set listeners to CSS Transition animation end or specific part
JavaScript
133
star
20

evil-blocks

Tiny framework for web pages to split your app to separated blocks
JavaScript
127
star
21

rails-sass-images

Sass functions and mixins to inline images and get images size
Ruby
114
star
22

compass.js

Compass.js allow you to get compass heading in JavaScript by PhoneGap, iOS API or GPS hack.
CoffeeScript
112
star
23

evil-front

Helpers for frontend from Evil Martians
Ruby
101
star
24

rake-completion

Bash completion support for Rake
Shell
63
star
25

yaspeller-ci

Fast spelling check for Travis CI
JavaScript
61
star
26

jquery-cdn

Best way to use latest jQuery in Ruby app
Ruby
59
star
27

sitnik.ru

My homepage content and scripts
JavaScript
57
star
28

pages.js

CoffeeScript
44
star
29

fotoramajs

Fotorama for Ruby on Rails
Ruby
44
star
30

about-postcss

Keynotes about PostCSS
Ruby
29
star
31

autohide-battery

GNOME Shell extension to hide battery icon in top panel, if battery is fully charged and AC is connected.
JavaScript
28
star
32

darian

Darian Mars calendar converter
Ruby
25
star
33

better-node-test

The CLI shortcut for node --test runner with TypeScript
JavaScript
25
star
34

plain_record

Data persistence with human readable and editable storage.
Ruby
24
star
35

evolu-lang

Programming language to automatically generate programs by evolution (genetic programming).
JavaScript
22
star
36

martian-logux-demo

TypeScript
17
star
37

hide-keyboard-layout

GNOME Shell extension to hide keyboard layout indicator in status bar
JavaScript
17
star
38

twitter2vk

Script to automatically repost statuses from Twitter to VK (В Контакте)
Ruby
16
star
39

asdf-cache-action

A Github Action to install runtimes by asdf CLI with a cache
15
star
40

ci-job-number

Return CI job number to run huge tests only on first job
JavaScript
15
star
41

print-snapshots

Print Jest snapshots to check CLI output of your tool
JavaScript
15
star
42

load-resources

Load all JS/CSS files from site website
JavaScript
15
star
43

susedko

Fedora CoreOS ignition config for my home server
JavaScript
14
star
44

file-container

Store different languages in one source file
JavaScript
14
star
45

postcss-isolation

Fix global CSS with PostCSS
14
star
46

autoprefixer-cli

CLI for Autoprefixer
JavaScript
14
star
47

d2na

D²NA language for genetic programming
Ruby
11
star
48

showbox

Keynote generator
JavaScript
11
star
49

boilerplates

Boilerplate for my open source projects
JavaScript
9
star
50

postcss-way

Keynotes about PostCSS way
9
star
51

gulp-bench-summary

Display gulp-bench results in nice table view
JavaScript
8
star
52

universal-layout

Универсальная раскладка Ситника
8
star
53

anim2012

Доклад «Анимации по-новому — лень, гордыня и нетерпимость»
CSS
8
star
54

nanopurify

A tiny (from 337 bytes) HTML sanitizer
JavaScript
7
star
55

ai

6
star
56

rit3d

Доклад «Веб, теперь в 3D: Практика»
CSS
6
star
57

dis.spbstu.ru

Department homepage
Ruby
5
star
58

jstransformer-lowlight

Lowlight support for JSTransformers
JavaScript
5
star
59

jest-ci

CLI for Jest test framework, but coverage only on first CI job
JavaScript
5
star
60

evolu-steam

Evolu Steam – evolutionary computation for JavaScript
JavaScript
5
star
61

insomnis

Текст блогокниги «Инсомнис»
4
star
62

plague

Blog/book Plague engine
Ruby
4
star
63

wsd2013

Презентация «Автопрефиксер: мир без CSS-префиксов»
Ruby
4
star
64

showbox-bright

Shower Bright theme for Showbox
JavaScript
3
star
65

ruby2jar

Ruby2Jar builds JAR from a Ruby script
Ruby
3
star
66

showbox-ai

Sitnik’s theme for ShowBox
CSS
3
star
67

showbox-shower

Shower for ShowBox
JavaScript
2
star
68

on_the_islands

Ruby
2
star