About
Live reloading (ie File sync) in the web means that the Browser automatically update/refresh the HTML page when you change files in your project (HTML, CSS, images, …)
List
Refresh at interval (Html / Javascript)
Reload the page at interval:
- With the Refresh http header, add this tag inside the head
<meta http-equiv="refresh" content="10">
- With Javascript
setInterval(function(){
window.location.reload();
}, 10000);
Injection
The below solution works by injecting code in the page that will open a channel with the server via a web socket. The server will then signal the refresh to the browser.
Application:
- Browsersync.io - serves the static content, detects changes, refreshes the browser, and offers many customizations.
- bundler internal dev server:
- for Webpack. See Webpack - Dev Server, WebPack - Hot Module Replacement
- for Grunt: Grunt-contrib-connect & grunt-contrib-watch
- How to use Chrome as an IDE with Chrome Workspace? - Chrome DevTools lets you change elements and styles on a web page and see your changes immediately.
- Idea: Live Edit
- Hugo (Static WebSite Generator) injects a LiveReload <script> before the closing </body> in the templates
- lite-server - Lightweight development only node server - wrapper around BrowserSync to make it easy to serve SPAs.
Library:
- https://github.com/mklabs/tiny-lr - LiveReload server implementation.
How the code injection is working ?
What the basis is of a Live Reload server 1)
- Server Side, create a Socket Server
var wss = new SocketServer({server})
chokidar
.watch('*.js')
.on('change', path => {
wss.clients.forEach(d => d.send('reload'))
})
- Client Side (in the HTML page)
new WebSocket(location.origin.replace(/^http/, 'ws'))
.onmessage = () => location.reload()
Configuration
Safe Write
To enable hot reloading, you need to disable safe write in your IDE. See https://webpack.github.io/docs/webpack-dev-server.html#working-with-editors-ides-supporting-safe-write
“Safe write” means changes are not written directly to original file but to temporary one instead, which is renamed and replaces original file when save operation is completed successfully. This behaviour causes file watcher to lose the track because the original file is removed. In order to prevent this issue, you have to disable “safe write” feature in your editor.