Skip to content

Instantly share code, notes, and snippets.

@carlosascari
Last active November 3, 2018 03:11
Embed
What would you like to do?
A pluggable live reload script. Works w/out a server
/**!
* A pluggable live reload script. No server required.
* Will reload page whenever the page content or link & script
* resources change.
* A reload will only be triggered when the page/window has focus.
*/
// https://gist.github.com/carlosascari/cc85e74544e4a26dcd88e94eb7a281ea
import $ from '$';
export default class Reloader {
constructor(watchInterval=1000) {
const resources = { '/': null, };
$('link[rel="stylesheet"]').forEach(elm => resources[elm.href] = null);
$('script[src]').forEach(elm => resources[elm.src] = null);
let checking = false;
let focused = true;
let waitForFocus = false;
window.onfocus = () => {
focused = true;
if (waitForFocus) {location.reload();}
waitForFocus = false;
};
window.onblur = () => {
focused = false;
waitForFocus = false;
};
setInterval(() => {
if (checking) return;
checking = true;
Promise.all(
Object.keys(resources)
.map(url => new Promise((ok, no) => {
fetch(url)
.then(r => r.text())
.then(src => {
if (resources[url] == null) {
resources[url] = src;
} else {
if (resources[url] !== src) {
if (focused) {
location.reload();
} else {
waitForFocus = true;
}
}
}
ok();
})
}))
)
.then(() => checking = false)
.catch(() => checking = false)
}, watchInterval);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment