web page hot reload in plain JavaScript + Apache & PHP

29 Apr 2019 | web page hot reload in plain JavaScript + Apache & PHP |

Hot re-loading, that is automatically updating the web page, when its content changes on the server, into the browser is a convenient developer aid for modern tooling like, webpack, AngularJS, ReactJS, VueJS etc.  I created   super simple  way  by just adding one JavaScript include at the bottom of your file and it works with a simple PHP file watcher which re-loads the  page on file changes.

Most of  these framework require extensive CLI setup that runs a hot reload server (typically a NodeJS web server), that basically injects a  the changed code into the <div id=app> </div> every time that the server detects a file content change.

Hot Reload – plain JavaScript

Of course the most simplest auto-reload is something like a <meta http-equiv="refresh" content="30">
but this is seldom useful since, just auto-refreshing the page isn’t always sensible.

How it works

This hot reload works, very simply there’s just two parts:

  • a JavaScript hotreload.js file that you include at the top of any web page <script src="hotreload.js"></script> that you want to automatically get reloaded when its content changes. It uses a standard long-poll approach to communicate with the file watcher script below.
  • a corresponding hotreload.php script  that sits on the server and watches the file for changes and automatically connects and informs the browser to reload when it detects a change.

That’s it, again keep in mind this is developer aid  and not designed for end-user purposes. Here’s the simples example of such a page.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>HTML5 Web Page</title>
  <meta name="description" content="HTML5 WebPage">
  <meta name="author" content="abrandao.com">
  <!-- link rel="stylesheet" href="css/styles.css" -->
  <script src="js/hotreload.js"></script>
</head>
<body>
 <h1>HTML5  Starter Page</h1>
<p> Save this page into any Apache w/PHP server </p>
<p> Anytime you change and save the page it will re-load the changes automatically in your browser </p>
</body>
</html>

 

How it differs from something like React hot-reload

Keep in mind this hot-reload awaits file changes and re-loads (refreshes ) the ENTIRE page. Many of the other hot-reload techniques are designed for Single Page Application (SPA) , where the app state is kept the same and only the changed code is injected into the  specific parts of the Single Page Application.   Because this reload the entire page, sate may not be maintained, unless you consciously save state within your page.

Another difference , in certain situations, where the code you’re writing has JavaScript errors, it might impeded the hot reload form working. This is why its advisable to put this code near the top of your page. But nevertheless the browser may simply stop all JavaScript code on errors, forcing you to have a manual reload.

The JavaScript client side

The code below is most of the JavaScript, it uses plain JavaScript (no JQuery or other dependencies) to issue an XMLHttpRequest to poll the data from the server file checker script. Here’s the partial code that does the work. The polling interval is set at 2000 ms (2 seconds) but can be adjusted to suit your needs.

setInterval( function() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
           if (xmlhttp.status == 200) {
 				//console.log(xmlhttp.responseText);
 				j=JSON.parse(xmlhttp.responseText);
 				console.log(j);
 				//if file changed RESTULT is TRUE we issue a 

 				if (j.hasChanged)
 				  { 
 					console.log("Changed!");
 				    window.location.reload(false); //reload this page
 				   }	
 				else
        console.log("No Change:");
 
 				
           }
           else if (xmlhttp.status == 400) {
              alert('error 400');
           }
           else {
               alert('Error '+xmlhttp.status );
           }
        }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

The PHP server side

The corresponding hotreload.php is the file watcher that issues an md5_file(filename)   and uses SESSIONS to keep track of the changing files. when the file does change it sends a notice to the calling script that the file has changed. Below is the core portions of the code.

if (@file_exists($filename))
   $md5_file=md5_file($filename);	//let's get the MD5 file info
else
die(json_encode("file [$filename] MISSING,filename does not exist. Check name and path ."));	
//now let's save the current file
 if  ( isset($_SESSION[$filename] )    ) //do we have this session set?
 {
    if ( $md5_file != $_SESSION[$filename] )
     $changed=true;
      $_SESSION[$filename] =$md5_file;  //update the session variable
 }
 else
 {
  $_SESSION[$filename] =$md5_file;
 }

Demo

To see  a demo click on this link: HotReload Demo   in this demo the default index.html page is randomly changed  on the server. It should change every few seconds.

Code on GitHub

I posted this code up on GitHub so check it out here HotReloadJS Github Code.

4 thoughts on “web page hot reload in plain JavaScript + Apache & PHP

  1. Reply Rossan Ugleriz Apr 29,2019 12:27 pm

    I’m building a Vue page , can I use this to reload my page while I’m developing it?

    • Reply Tony B. Apr 30,2019 3:01 pm

      Yes, you can use it to develop with VUe , just include the VUE from a CDN, or really anywhere and when you save changes to the page it will update

  2. Reply Pierce Bosque May 10,2019 9:17 am

    Does this still work , if there Javascript errors on this page?

    • Reply Tony B. May 14,2019 9:27 am

      Yes in many cases when you please this within the tag it should run