var cache = {};
function createScript(options) {
  var script = document.createElement('script');
  script.type = options.type || 'text/javascript';
  script.async = !!options.async;
  script.id = options.id || options.url;
  if (options.url) {
    script.src = options.url;
  }
  if (options.text) {
    script.text = options.text;
  }
  return script;
}
function loadScript(head, script) {
  return new Promise(function (resolve, reject) {
    // Handle Script loading
    var done = false;

    // Attach handlers for all browsers.
    //
    // References:
    // http://stackoverflow.com/questions/4845762/onload-handler-for-script-tag-in-internet-explorer
    // http://stevesouders.com/efws/script-onload.php
    // https://www.html5rocks.com/en/tutorials/speed/script-loading/
    //
    script.onload = script.onreadystatechange = function () {
      if (!done && (!script.readyState || script.readyState === 'loaded' || script.readyState === 'complete')) {
        done = true;
        script.onload = null;
        resolve(script);
      }
    };
    script.onerror = reject;
    head.appendChild(script);
  });
}
function getScriptById(id) {
  var script = id && document.getElementById(id);
  if (script) {
    return script;
  }
}
function getScriptByUrl(url) {
  var script = url && document.querySelector("script[src='" + url + "']");
  if (script) {
    return script;
  }
}
export default function exec(options, parent) {
  if (typeof options === 'string') {
    options = {
      url: options,
      debug: false
    };
  }
  var cacheId = options.id || options.url;
  var cacheEntry = cache[cacheId];
  if (cacheEntry) {
    if (!!options.debug) {
      console.log('load-js: cache hit', cacheId);
    }
    return cacheEntry;
  }
  if (options.allowExternal !== false) {
    var el;
    if (options.id) {
      el = getScriptById(options.id);
    }
    if (!el) {
      el = getScriptByUrl(options.url);
    }
    if (el) {
      var promise = Promise.resolve(el);
      if (cacheId) {
        cache[cacheId] = promise;
      }
      return promise;
    }
  }
  if (!options.url && !options.text) {
    throw new Error('load-js: must provide a url or text to load');
  }
  return loadScript(parent, createScript(options));
}