visibilityjs
2.0.2 • Public • PublishedVisibility.js is a wrapper for thePage 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 toa user or hidden in background tab or prerendering. It allows you to usethe page visibility state in JavaScript logic and improve browser performanceby disabling unnecessary timers and AJAX requests, or improve user interfaceexperience (for example, by stopping video playback or slideshow when userswitches to another browser tab).
Moreover, you can detect if the browser is justprerendering the page whilethe user has still not opened the link, and don’t count this as a visit in youranalytics module, or do not run heavy calculations or other actions which willdisable the prerendering.
Page Visibility API isnatively supported by all browsers. For old browsersyou can uselib/visibility.fallback.js
with focus/blur hack (note that thishack has an issue: when browser just lose focus but still visible for user, its state will change to [hidden]).
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 openedby 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 whencontent is visible to the user, i.e. the ones animating a countdown animation.
Visibility.every(interval, callback)
is similar tosetInterval(callback, interval)
, but callscallback
everyinterval
ms onlyif 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 pageis hidden. In next example, a check for inbox updates will be run every 1 minutefor 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 thanthe visible interval, it will be called immediately. In the example above, if youhid 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 thesetInterval
function. However, it cannot be passed to clearInterval
, and you should useVisibility.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
willfall back tosetInterval
, and callback
will be run everyinterval
ms forboth the hidden and visible pages.
Initializers
Another common use case is when you need to execute some actions upon a switch toparticular visibility state.
Waiting until the page becomes visible
Visibility.onVisible(callback)
checks current state of the page. If it isvisible now, it will runcallback
, otherwise it will wait until state changestovisible
, and then runcallback
.
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 untilthe page becomes visible, i.e. until the user has switchedto a tab with the page:
Visibility.onVisible(function () {startIntroAnimation();});
If a browser doesn’t support Page Visibility API,Visibility.onVisible
will run thecallback
immediately.
Wait until the page is opened after prerendering
A web developer can hint a browser (using Prerendering API) that an useris 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 willnot wait after actually going via the link.
But you may not want to count the browser prerendering a page as a visitor inyour analytics system. Moreover, the browser will disable prerendering if youwill try to do heavy computations or use audio/video tags on the page. So, youmay decide to not run parts of the code while prerendering and wait until theuser actually opens the link.
You can useVisibility.afterPrerendering(callback)
in this cases. For example,this code will only take real visitors (and not page prerenderings) intoaccount:
Visibility.afterPrerendering(function () {Statistics.countVisitor();});
If the browser doesn’t support Page Visibility API,Visibility.afterPrerendering
will runcallback
immediately.
Low-level API
In some cases you may need more low-level methods. For example, you may want tocount the time user has viewed the page in foreground and time it has stayed inbackground.
Visibility.isSupported()
will returntrue
if browser supports thePage Visibility API:
if( Visibility.isSupported() ) {Statistics.startTrackingVisibility();}
Visibility.state()
will return a string with visibility state. More statescan be added in the future, so for most cases a simplerVisibility.hidden()
method can be used. It will returntrue
if the page is hidden by any reason.For example, while prerendering,Visibility.state()
will return"prerender"
,but Visibility.hidden()
will returntrue
.
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 avisible tab (not a background one):
$(document).load(function () {if ( !Visibility.hidden() ) {VideoPlayer.play();}});
UsingVisibility.change(callback)
you can listen to visibility state changingevents. Thecallback
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);});
Methodchange
returns listener ID. You can use it to unbind listener byVisibility.unbind(id)
:
var listener = Visibility.change(function (e, state) {if ( !Visibility.hidden() ) {VideoPlayer.pause();}});VideoPlayer.onFinish(function () {Visibility.unbind(listener);});
MethodsonVisible
andafterPrerendering
will also return listener ID,if they wait visibility state changes. If they execute callback immediately,they returntrue
if Page Visibility API is supported andfalse
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.timers
–every
andstop
methods to setsetInterval
dependon visibility state.visibility
–visibility.core
andvisibility.timers
together.visibility.fallback
– fallback for browser without Page Visibility API.It use documentfocus
/blur
events, so document become to be hidden,when browser just lose focus, but still visible for user.
Installing
Available byNPM:
npm install --save visibilityjs
Contributing
To run tests you need node.js and npm. For example, in Ubuntu run:
sudo apt-get install nodejs npmNext install npm dependencies:
npm installRun all tests:
npm testAlso you can see real usage example in integration test
test/integration.html
.
Package Sidebar
Install
npm i visibilityjs
Repository
Weekly Downloads
185,847
Version
2.0.2
License
MIT
Unpacked Size
28.2 kB
Total Files
10