forked from remy/polyfills
-
Notifications
You must be signed in to change notification settings - Fork 0
/
offline-events.js
47 lines (40 loc) · 1.07 KB
/
offline-events.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
// Working demo: http://jsbin.com/ozusa6/2/
(function () {
function triggerEvent(type) {
var event = document.createEvent('HTMLEvents');
event.initEvent(type, true, true);
event.eventName = type;
(document.body || window).dispatchEvent(event);
}
function testConnection() {
// make sync-ajax request
var xhr = new XMLHttpRequest();
// phone home
xhr.open('HEAD', '/', false); // async=false
try {
xhr.send();
onLine = true;
} catch (e) {
// throws NETWORK_ERR when disconnected
onLine = false;
}
return onLine;
}
var onLine = true,
lastOnLineStatus = true;
// note: this doesn't allow us to define a getter in Safari
navigator.__defineGetter__("onLine", testConnection);
testConnection();
if (onLine === false) {
lastOnLineStatus = false;
// trigger offline event
triggerEvent('offline');
}
setInterval(function () {
testConnection();
if (onLine !== lastOnLineStatus) {
triggerEvent(onLine ? 'online' : 'offline');
lastOnLineStatus = onLine;
}
}, 5000); // 5 seconds, made up - can't find docs to suggest interval time
})();