title: jQuery ajaxError() handler fires if user leaves page before page finishes loading
body: <p>We use jQuery's global ajaxError() handler to alert the user of any AJAX failures:</p>
  
  <pre><code>$(document).ajaxError(function() {  
      $("There was a network or server error. Please try again later.").dialog({  
          title: "Error",  
          modal: true,  
          resizable: false,  
          buttons: { 'Ok': function() { (this).dialog("close"); } }  
      });  
  });  
  </code></pre>
  
  <p>Unfortunately, this global error handler also fires if the user leaves the page before it finishes loading. Here are the steps to reproduce the error:</p>
  
  <ol>
  <li>User visits Page A, which includes elements that load via AJAX.</li>
  <li>AJAX elements on Page A begin loading.</li>
  <li>User clicks link to visit Page B <em>before</em> AJAX elements on Page A have finished loading.</li>
  <li>The error dialog box appears briefly before the browser redirects to Page B.</li>
  </ol>
  
  <p>Any idea how we can get ajaxError() not to trigger when the error is directly caused by the user visiting a new page?</p>
  
  <p>UPDATE: Here's my code now, after incorporating the suggestions in the comments:</p>
  
  <pre><code>// I added a 3 second delay to our error dialog, enough time
  // for the user to leave for a new page:
  $(document).ajaxError(function() {
      setTimeout(my_error_handler, 3000);
  });
  
  // Warn user before leaving page if AJAX is still loading.
  // Not sure I'll keep this:
  $(document).ajaxStart(function() {
      ajaxing = true;
  });
  
  $(document).ajaxStop(function() {
      ajaxing = false;
  });
  
  window.onbeforeunload = function() {
      if (typeof(ajaxing) != 'undefined' &amp;&amp; ajaxing) {
          return "Page elements are still loading!";
      }
  };
  </code></pre>