Skip to content

Instantly share code, notes, and snippets.

@adamjgrant
Last active July 6, 2017 07:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamjgrant/1bcef051eb265f9de3a5a9504249e87e to your computer and use it in GitHub Desktop.
Save adamjgrant/1bcef051eb265f9de3a5a9504249e87e to your computer and use it in GitHub Desktop.

Stupidly simple live editing

This is a nice and simple script I like to use when I'm heads down on front end development. All this does is automatically reload the page every 2 seconds.

What I love most about this is that I can just open any text editor, and just double click on the html file being edited to view in a browser. No building, cloning, or plugins needed and it works on any OS.

<h1>My page</h1>
<script>
var live = true;
setInterval(() => {
if (live) location.reload();
}, 2000);
</script>

Fancier and Schmancier

But if you find it annoying to see your browser reload every two seconds, here's a more complex method that refreshes only if the page has changed.

This method just does an ajax request to itself and refreshes if it changed since the last attempt. I increased the timeout to 1 second as we won't be constantly refreshing anyway.

var live = true,
lastResponse = "";
setInterval(() => {
var xhr = new XMLHttpRequest;
xhr.open("GET", location.href + "?v=" + Math.random(), true);
xhr.onload = function() {
if (live && this.response != lastResponse && lastResponse != "") location.reload();
lastResponse = this.response;
}
xhr.send();
}, 1000)

Golfed version

Or if you just want an easy copypasta version to throw in any HTML file, here another version with reduced characters. It also does not allow for toggling a live value. Then again, it's easy enough to just add a // in front of this one-liner.

a="";setInterval(()=>{b=new XMLHttpRequest;b.open("GET",location.href+"?v="+Math.random(),true);b.onload=function(){if(this.response!=a&&a!=""){location.reload();}a=this.response;};b.send();},1000)
@AlexNodex
Copy link

Doesn't really help for linked CSS / Javascript unless you're incrementing your build numbers....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment