-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhotcake.js
91 lines (79 loc) · 2.21 KB
/
hotcake.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
/*!
* Copyright (c) 2020 Xvezda <[email protected]>
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/* global XMLHttpRequest */
(function (window, document) {
var initialized = false;
function normalizeUrl (url) {
var virtualLink = document.createElement('a');
virtualLink.href = url;
return virtualLink.href;
}
function poll (url, callback) {
var xhr = new XMLHttpRequest();
var newUrl = url + ((url.indexOf('?') !== -1 ? '&' : '?') +
(new Date()).getTime());
xhr.open('GET', newUrl);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function (event) {
switch (xhr.readyState) {
case XMLHttpRequest.DONE:
callback(event.target.response, url);
break;
default:
// throw new Error('unexpected state code')
break;
}
};
xhr.send(null);
}
function Hotcake (options) {
initialized = true;
var cache = {};
var defaultOptions = {
mode: 'parallel',
observe: ['./'],
interval: 3000
};
options = options || {};
for (var key in defaultOptions) {
if (!(key in options)) {
options[key] = defaultOptions[key];
}
}
function polling (url) {
setTimeout(function () {
poll(url, function (response) {
var key = normalizeUrl(url);
var oldData = cache[key];
var newData = response;
if (oldData !== undefined && oldData !== newData) {
return window.location.reload();
}
cache[key] = newData;
polling(url);
});
}, options.interval);
}
// Initialize caches
for (var i = 0; i < options.observe.length; ++i) {
poll(options.observe[i], function (response, url) {
cache[normalizeUrl(url)] = response;
polling(url);
});
}
}
// Expose
if (typeof window !== 'undefined' && !('Hotcake' in window)) {
window.Hotcake = Hotcake;
}
window.onload = function (event) {
if (!initialized) {
window.Hotcake.o = new Hotcake(); // Active instance
}
};
})(window, document);