0

From this page I got a great answer, see below the code. One problem occurs for me.

This script is checking itself. The code is in index.html and it will check if there are changes on index.html. If there are changes, it should refresh itself. It all works, but it stays in the same condition.

So if you change the file once, it will loop saying 'the site has been modified' and refresh. Does anbody know how to solve this?

<html>
  <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script type="text/javascript">
      var checkUrl="index.html";
      var firstCheck = false;
      window.setInterval("checkForUpdate()", 1000);

      function checkForUpdate() {
          $.ajax(checkUrl, {
              ifModified : true,
              type : 'HEAD', 

              success : function (response) {
                  if(firstCheck === false) {
                      firstCheck = true;
                      return;
                  }
                  $('#output').html('the site has been modified');
              }
          }); 
      }    
   </script> 
  </head>
  <body>
    <div id="output">Not Modified</div>
  </body>
</html>
Community
  • 1
  • 1
Joep
  • 112
  • 2
  • 10
  • What happens if you try using `GET` or `POST` instead of `HEAD` for your request type? http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings implies HEAD may not be fully supported – Josh Harrison Nov 25 '13 at 14:59

1 Answers1

1

The source of your code acknowledges that it doesn't work and offers a replacement solution:

var checkUrl="test.txt";
window.setInterval("checkForUpdate()", 1000);
var pageLoad = new Date().getTime();

function checkForUpdate() {
    $.ajax(checkUrl, {
        type : 'HEAD',
        success : function (response, status, xhr) {
            if(firstCheck === false) {
                firstCheck = true;
                return;
            }
            // if the server omits the 'Last-Modified' header
            // the following line will return 0. meaning that
            // has not updated. you may refine this behaviour...
            var lastModified = new Date(xhr.getResponseHeader('Last-Modified'))
                .getTime();
            if(lastModified > pageLoad) {
                $('#output').html('the site has been modified');
            }
        }
    }); 
}  
David Braun
  • 5,573
  • 3
  • 36
  • 42
  • It seems to work if I delete the `if(firstCheck === false) { firstCheck = true; return; }` – Joep Nov 25 '13 at 15:37