Skip to content

Instantly share code, notes, and snippets.

@TianyiLi
Created July 1, 2019 14:04
Show Gist options
  • Save TianyiLi/165866abe2834971ba135c469e1258fa to your computer and use it in GitHub Desktop.
Save TianyiLi/165866abe2834971ba135c469e1258fa to your computer and use it in GitHub Desktop.
very simple live reload
// <![CDATA[ <-- For SVG support
if ('WebSocket' in window) {
(function () {
function refreshCSS () {
var sheets = [].slice.call(document.getElementsByTagName("link"));
var head = document.getElementsByTagName("head")[0];
for (var i = 0; i < sheets.length; ++i) {
var elem = sheets[i];
head.removeChild(elem);
var rel = elem.rel;
if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") {
var url = elem.href.replace(/(&|\?)_cacheOverride=\d+/, '');
elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date().valueOf());
}
head.appendChild(elem);
}
}
// var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://';
var address = /* protocol + window.location.host + window.location.pathname */ 'ws://localhost:33314/ws';
var socket = new WebSocket(address);
socket.onmessage = function (msg) {
if (msg.data == 'reload') window.location.reload();
else if (msg.data == 'refreshcss') refreshCSS();
};
console.log('Live reload enabled.');
})();
}
// ]]>
{
"name": "auto-refresh",
"version": "1.0.0",
"description": "",
"main": "inject.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"chokidar": "^3.0.1",
"ws": "^7.0.1"
}
}
const chokidar = require('chokidar')
const ws = require('ws')
const wss = new ws.Server({
port: 33314,
path: '/ws'
})
wss.on('connection', (w) => {
chokidar.watch('.', { ignored: /(^|[\/\\])\../ })
.on('change', (path) => {
if (!!~path.indexOf('.html')) {
w.send('reload')
}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment