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>
1

1 Answer 1

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');
            }
        }
    }); 
}  
1
  • It seems to work if I delete the if(firstCheck === false) { firstCheck = true; return; }
    – Joep
    Nov 25, 2013 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.