'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var isUrl = _interopDefault(require('./isUrl'));
var getStringHash = _interopDefault(require('./getStringHash'));
var _shared = require('./_shared');

/**
 * 动态加载js脚本文件
 * @param {string} src
 * @param {boolean} reload
 *
 * @example
 * loadScript('https://s1.hdslb.com/bfs/static/laputa-home/client/assets/svgfont.6beb9aeb.js');
 */
function loadScript(src, reload) {
  return new Promise(function (resolve, reject) {
    if (!isUrl(src)) return reject(new Error('src不是一个正确的url地址！'));
    var scriptId = "bs_url_".concat(getStringHash(src));
    _shared.cachedStyleOrScript(scriptId, reload, false).then(function (cached) {
      if (cached) return resolve();
      var scriptEl = document.createElement('script');
      scriptEl.id = scriptId;
      scriptEl.type = 'text/JavaScript';
      scriptEl.src = src;

      scriptEl.onload = function () {
        return resolve();
      };

      scriptEl.onreadystatechange = function () {
        if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
          resolve();
        }
      };

      document.querySelector('head').appendChild(scriptEl);
    });
  }).then();
}

module.exports = loadScript;
