How to Make Your Own Live-Reloader

Mert Akengin
mert’s blog
2 min readJul 7, 2017

--

I bet you already saw couple of these things in frameworks you use if you read this article. Basically the what plugin do is when you change some local file it reloads/refreshes browser so changes are visible immediately without user action.

But these plugins require heavy frameworks most of the time and if you are doing very simple HTML only webpage it is a burden to install all those gulp-grunt stuff and having 10+ megabytes of stuff where your actual data is not even few kilobytes.

Ingredients:
- A Browser
- A Text Editor
- A Websocket Server
- A HTTP Server

I assume first two is already satisfied and for last two it is relatively easy. I’ll be using websocketd for those purposes. But you can use your own language or framework or app if it provides websocket and http server.

Please beware that in this post, I won’t inject anything to the HTML pages that are served, instead you will add JS code into your page. And since we are in the era of single-page (progressive) web apps, I think index.html is enough.

new WebSocket("ws://localhost:8000").onmessage = function(e) {
window.location.reload()
return
}

After that, you need to run web server stuff for that you can download websocketd . There is already precompiled binaries at http://websocketd.com.

Also you need to install fswatch utility, which will watch our files for changes. You can install it through Homebrew, http://brew.sh for macOS.
And for Linux I recommend inodenotify but you can use another of course.

First cd into directory you want to publish then execute this command:
websocketd --port=8000 --staticdir=. fswatch -1r .

When you open your browser and go to http://localhost:8000/ you should see list of your files. You can click-to-open your index, which will load JS code to connect Websocket and wait for changes.

Note:
If you want secured (SSL) server you can change websocket schema to the wss and add these parameters before staticdir to your websocket server:
--ssl --sslkey=/path/to/ssl.key --sslcert=/path/to/ssl.crt

--

--

Mert Akengin
mert’s blog

Devops & Systems Engineer, #linux power user, #c dev,