JSFiddle - React, Tailwind, and code Playground

by maremp

HTML

<div id="log"></div>

JavaScript

// check if given url is `application/javascript`, calls callback if it is
function checkIfUrlIsScript(url, callback) {
  $.ajax({
    type: "HEAD",
    url: url,
  }).done(function(message, text, jqXHR){
    // check if response is 200 (OK)
    var isStatusOk =  jqXHR.status === 200 
    if (!isStatusOk) {
      return;
    }
    // check if content-type contains application/javascript
    var isScript = jqXHR.getResponseHeader('Content-Type').indexOf('application/javascript') !== -1
    if (!isScript) {
      return;
    }
    // check if callback exist to prevent calling `undefined` as a function
    if (callback) {
       callback(url);
    }
  })
}

var urls = [
  'https://code.jquery.com/jquery-3.1.0.js',
  'https://stackoverflow.com/',
  'https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js'
]

function urlIsScriptCallback(url) {
	document.getElementById('log').insertAdjacentHTML( 'beforeend', '<p>url "' + url + '" is a script</p>');
}

// callback will not be called for "http://stackoverflow.com/",
// because Access-Control-Allow-Origin is not present in response,
// therefore request is blocked by browser.
// you can catch this with `.fail`, but this won't stop the error
// from showing inside browser's console
urls.forEach(function (url) {
  checkIfUrlIsScript(url, urlIsScriptCallback);
})