-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlive-reload-browser.js
50 lines (44 loc) · 1.72 KB
/
live-reload-browser.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
/* eslint no-console: 0 */
import throttle from './throttle.js'
// Options
let hugeConsoleAlertStyle = 'background: hsla(0, 20%, 5%, 1); color: hsla(0, 100%, 90%, 1); padding: 1em; font-size: 2em;'
let defaultLiveReloadPath = '/dev/api/client-code-last-modified'
let pollIntervalMs = 1000
// State
let clientLastRefreshedDate = new Date()
let sequentialFailures = 0
let liveReloadTick = async ()=>{
if (sequentialFailures >= 5) return false
fetch(defaultLiveReloadPath).then(res => {
res.text().then(sourceDateModifiedStr => {
if (!sourceDateModifiedStr){ return false }
let resDate = Number(sourceDateModifiedStr)
if (resDate && resDate >= Number(clientLastRefreshedDate)){ // Client update time is later than our last refresh
console.warn('%c BROWSER CLIENT CODE OBSOLETE -- REFRESHING PAGE NOW.', hugeConsoleAlertStyle)
clearInterval(liveReloadTick)
clientLastRefreshedDate = new Date()
location.reload(true) // `true` makes it a forced reload; ignore cache
}
})
}, err => {
console.error(err)
sequentialFailures += 1
if (sequentialFailures >= 5){
clearInterval(liveReloadTick)
console.warn(`Live reload failed to connect ${sequentialFailures} times in a row; assuming the server's down.`)
} else {
console.warn(`Live reload failed to connect to ${defaultLiveReloadPath} - trying again…`)
liveReloadTick()
}
})
}
setInterval(liveReloadTick, pollIntervalMs)
let restart = throttle(()=>{
sequentialFailures = 0
setInterval(liveReloadTick, pollIntervalMs)
}, 1000)
// If we detect user activity, try and restart the live reloading connection attempts
document.addEventListener('focusin keydown scroll', ()=>{
restart()
})
console.info('Injected src-change-reload browser script before </body>.')