This repository has been archived by the owner on Apr 4, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
128 lines (112 loc) · 2.18 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/**
* document.
*/
var doc = document;
/**
* Execute the provided `fn`
* when the page visibility changes.
*
* if a function is not provided an
* api will be returned of 3 methods
* that each accept a callback that will
* be invoked.
*
* example:
*
* // option a
* visiblity(function (e, state) {
* if ('prerender' == state) dostuff();
* });
*
* // option b
* visiblity()
* .prerender(function (e) {})
* .visible(function (e) {})
* .hidden(function (e) {});
*
* @param {Function} fn optional
* @return {Object} api
*/
exports = module.exports = function (fn) {
var vendors = ['ms', 'moz', 'webkit']
, event = 'visibilitychange'
, state = 'visibilityState'
, len = vendors.length
, curr;
// not supported.
if (!doc.addEventListener) return exports;
// capture prefix.
while (curr = vendors[--len]) {
if (doc[curr + state]) {
event = curr + event;
state = curr + state;
break;
}
}
// attach handle.
doc.addEventListener(event, function (e) {
var cb = fn;
// delegate
if (cb) return cb(e, doc[state]);
// fn
switch (doc[state]) {
case 'prerender':
cb = exports._prerender;
break;
case 'visible':
cb = exports._visible;
break;
case 'hidden':
cb = exports._hidden;
break;
}
cb && cb(e);
}, false);
// api
return exports;
};
/**
* Set prerender callback.
*
* example:
*
* visibility()
* .prerender(function (e) {});
*
* @param {Function} fn
* @return {visibility}
*/
exports.prerender = function (fn) {
exports._prerender = fn;
return exports;
};
/**
* Set visible callback.
*
* example:
*
* visibility()
* .visible(function (e) {});
*
* @param {Function} fn
* @return {visibility}
*/
exports.visible = function (fn) {
exports._visible = fn;
return exports;
};
/**
* Set hidden callback.
*
* example:
*
* visibility()
* .hidden(function (e) {});
*
* @param {Function} fn
* @return {visibility}
*/
exports.hidden = function (fn) {
exports._hidden = fn;
return exports;
};