“Live Reload”-like feature with a single line of javascript
Since so much of front-end web development is trial-and-error, seeing code changes visualized in realtime is a huge time-saver. Seeking this advantage, I’ve spent many months looking for a simple plugin that can get the job done but I’ve had no luck so far. Tincr doesn’t work with the latest Chrome and even before that I couldn’t get it work on Windows 8. Other plugins start up local servers in the background or you have to switch to an entirely new editor like Brackets (which again uses a node server in the background) just for the Live Reload feature. And even then things aren’t perfect; Brackets Live Reload, for example, breaks if you open the browser’s developer tools.
I initially tried to solve the Live Reload problem using a simple page refresh every 5 seconds:
<meta http-equiv=“refresh” content=“5”>
But this has very bad side-effects. For example, I can no longer use the browser’s developer tools since it’d restart with the page refresh happening every 5 seconds. I could lengthen the interval but then I might just as well manually refresh.
After giving it some thought, I finally have a solution that gives me something much closer to what I want while not having any of the downsides of the other approaches — refreshing the page when the window gets focus. This way I can simply alt-tab from Sublime Text to the browser and the page refreshes immediately. No cumbersome plugins, node servers or special editors required; just this javascript one-liner is all that’s needed:
window.onfocus = function() { location.reload() }
And since Sublime Text has the option to save when the editor loses focus…
“save_on_focus_lost”: true
…I don’t even have to press Ctrl-S like I have to with Live Reload plugins.
The only caveat is that you need to remember to edit the javascript function out when you push the page to production.