CORS in JSFiddle

by Rohit K

HTML

<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
Ping server using
<select id="approachOptions">
  <option value="ajax">AJAX</option>
  <option value="image">Image Trick</option>
  <option value="jsonp">JSONP</option>
  <option value="getscript">$.getScript()</option>
</select>
<table>
  <tr>
    <th>Website</th>
    <th>Status</th>
    <th>Uptime</th>
  </tr>
  <tr>
    <td>Google</td>
    <td>
      <label id="googleStatus"></label>
    </td>
    <td></td>
  </tr>
  <tr>
    <td>Dummy Site</td>
    <td>
      <label id="dummySiteStatus"></label>
    </td>
    <td></td>
  </tr>
  <tr>
    <td>JS Fiddle</td>
    <td>
      <label id="jsfiddleStatus"></label>
    </td>
    <td></td>
  </tr>
  <tr>
    <td>Lorem Pixel</td>
    <td>
      <label id="loremStatus"></label>
    </td>
    <td></td>
  </tr>
</table>

CSS

table {
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border-bottom: 1px solid black;
}

JavaScript

var sites = {
  google: {
    url: "https://www.google.com",
    id: "googleStatus"
  },
  dummy: {
    url: "http://www.dummysitealphabeta2.com",
    id: "dummySiteStatus"
  },
  jsfiddle: {
    url: "https://fiddle.jshell.net",
    id: "jsfiddleStatus"
  },
  lorem: {
    url: "https://lorempixel.com/400/200/",
    id: "loremStatus"
  }
};

// Default
refreshAllSites('ajax');

function refreshAllSites(approach) {
  Object.keys(sites).forEach(function(name) {
    // Four approaches
    switch (approach) {
      case "ajax":
        // 1. Using AJAX (works only for the same origin)
        checkStatusUsingAJAX(sites[name]);
        break;

      case "image":
        // 2. Using Image trick (works only if 
        // the remote server returns image)
        checkStatusUsingImage(sites[name]);
        break;

      case "jsonp":
        // 3. Using JSONP (Doesn't work because server is an HTML page)
        checkStatusUsingJSONP(sites[name]);
        break;

      case "getscript":
        // 4. Using GetScript (Doesn't work for lorem pixel because its MIME type ('image/jpeg') is not executable.)
        checkStatusUsingGetScript(sites[name]);
        break;
    }
  });
}

// Approach 4: Using GetScript
function checkStatusUsingGetScript(site) {
  $.getScript(site.url + "?callback=?").done(function() {
    document.getElementById(site.id).innerHTML = "Up"
  }).fail(function() {
    document.getElementById(site.id).innerHTML = "Down"
  });
}

// Approach 3: Using JSONP
// Doesn't work as server returns an HTML page
function checkStatusUsingJSONP(site) {
  jsonp(site.url, function() {
    document.getElementById(site.id).innerHTML = "Up"
  }, function() {
    document.getElementById(site.id).innerHTML = "Down"
  });

  // Define JSONP
  function jsonp(url, success, fail) {
    var callbackName = 'jsonpCallback' +
      Math.round(10000 * Math.random());

    window[callbackName] = function(data) {
      console.log("calling callback");
      delete...