Skip to content

Instantly share code, notes, and snippets.

@khalidx
Last active May 30, 2021 08:09
Show Gist options
  • Select an option

  • Save khalidx/35a89d2efc5fb2e08cf866f7b254957a to your computer and use it in GitHub Desktop.

Select an option

Save khalidx/35a89d2efc5fb2e08cf866f7b254957a to your computer and use it in GitHub Desktop.
A simple live-reload implementation that refreshes the page when the source file changes on disk.

A simple live-reload implementation that refreshes the page when the source file changes on disk.

The server.js file just serves the files in the directory that it is in, including itself. It also ensures that a private Cache-Control header is set for GET requests, and caching disabled for other HTTP methods.

The index.html file contains a hand-rolled live-reload script that polls the server every 2 seconds and honors the HTTP 304 response code and the caching and etag directives specified by the server.

This can also run as a zero-dependency implementation of live-reload by removing JQuery and Express from the example code and using plain JavaScript DOM methods and the built-in Node.js HTTP server.

Run the server with:

node server.js

Edit the index.html file and watch the page reload only when the file changes. Check the browser log and network console to see what's going on under the hood.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>index</title>
</head>
<body>
<p id="now"></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"></script>
<script>
function whenTheDocumentIsReady (doSomething) {
$(document).ready(doSomething);
}
function showTheCurrentTimestamp () {
$("#now").text(Date.now());
}
function everyTwoSeconds (doSomething) {
setInterval(doSomething, 2000);
}
var isFirstRequest = true;
function refreshIfChanged () {
$.get({
url: window.location.href,
ifModified: true,
statusCode: {
304: function () {
console.log("304 Not Modified");
},
200: function () {
if (isFirstRequest) {
isFirstRequest = false;
} else {
location.reload();
}
}
}
});
}
whenTheDocumentIsReady(function () {
showTheCurrentTimestamp();
everyTwoSeconds(refreshIfChanged);
});
</script>
</body>
</html>
#!/usr/bin/env node
const express = require('express')
express()
.use(function (req, res, next) {
console.log('request', Date.now())
if (req.method == 'GET') {
res.set('Cache-Control', 'private, max-age=0, no-cache')
} else {
res.set('Cache-Control', 'no-store')
}
next()
})
.use('/', express.static(__dirname))
.listen(80, function () {
console.log('listening...')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment