title: Check if online resource is reachable with JavaScript, not requiring the The Same Origin Policy to allow it
body: <p>I want to check if a server is <em>reachable</em> with a JavaScript function.</p>
  
  <p>By <em>reachable</em>, I mean, if the server answers, I don't care which HTTP status code, it's reachable.</p>
  
  <p>Stackoverflow/Google helped me to this function:</p>
  
  <pre><code>function check(target)
  {
      var xhr = new XMLHttpRequest();
      var target = "https://"+target+"/index.php";
      var num = Math.round(Math.random() * 10000);
  
      xhr.open("HEAD", target + "?num=" + num, true);
      xhr.send();
      xhr.addEventListener("readystatechange", processRequest, false);
  
      function processRequest(e)
      {
        if (xhr.readyState == 4)
        {
          if (xhr.status !== 0)
          {
            return true;
          }
          else
          {
            return false;
          }
        }
      }
  }
  </code></pre>
  
  <p>Which works just fine, if the target allows the action with <code>Access-Control-Allow-Origin: *</code> (or the client specifically). But that is not the case.</p>
  
  <p>I've come across a number of solutions, which all seem to rely on that.</p>
  
  <p>How can I check if a server is reachable, independent of the <code>Access-Control-Allow-Origin</code> settings on the server, with JavaScript?</p>
  
  <p><em>edit:</em> I just wanted to add, that I can not modify the target (e.g. change headers), but I'm able to identify resources that are supposed to be available (e.g. <a href="https://target/this-specific-site.php" rel="noreferrer">https://target/this-specific-site.php</a>)</p>
  
  <p><em>edit2:</em> I'm trying to implement a solution, as suggested by @Vic; <a href="https://jsfiddle.net/ZuaP8/22/" rel="noreferrer">try it here</a>:</p>
  
  <pre><code>function chk(){
  
  var img = new Image();   // Create new image element
  
  img.onload = function(){
      return false;
  };
  
  img.onerror = function() {
      return true;
  };
  
  // Try to change this URL to nonexistant image
  img.src = 'https://www.google.com/images/srpr/logo3w.png'; // Set source path
  
  }
  
  if (chk())
  {
  alert("IMAGE LOADED");
  }
  else
  {
  alert("IMAGE FAILED TO LOAD ("+chk()+")");
  }
  </code></pre>
  
  <p>but the function appears to return <code>undefined</code>, so the check fails.</p>
  
  <p><em>edit3:</em> I need the function to give me a return value.</p>