All files / io getScript.js

100% Statements 22/22
52.63% Branches 10/19
66.67% Functions 2/3
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                                    2x   2x 2x 2x 2x 2x   2x 2x 2x   2x 2x   2x 2x         2x 2x   2x 2x 2x     2x 2x 2x     1x  
/**
 * 加载 script 文件
 * @method io/getScript
 * @param {Object} options 选项
 * @param {String} options.src script 地址
 * @param {String} [options.charset='utf-8'] script 编码
 * @param {Function} [options.onLoad] script 加载完成的回调函数
 * @example
 * var $getScript = require('@spore-ui/kit/packages/io/getScript');
 * $getScript({
 *   src: 'https://code.jquery.com/jquery-3.3.1.min.js',
 *   onLoad: function () {
 *     console.info(window.jQuery);
 *   }
 * });
 */
 
function getScript(options) {
  options = options || {};
 
  var src = options.src || '';
  var charset = options.charset || '';
  var onLoad = options.onLoad || function () {};
  var wtop = options.wtop || window;
  var doc = wtop.document;
 
  var script = doc.createElement('script');
  script.async = 'async';
  script.src = src;
 
  Eif (charset) {
    script.charset = charset;
  }
  script.onreadystatechange = function () {
    Eif (
      !this.readyState
      || this.readyState === 'loaded'
      || this.readyState === 'complete'
    ) {
      Eif (typeof onLoad === 'function') {
        onLoad();
      }
      this.onload = null;
      this.onreadystatechange = null;
      this.parentNode.removeChild(this);
    }
  };
  script.onload = script.onreadystatechange;
  doc.getElementsByTagName('head')[0].appendChild(script);
  return script;
}
 
module.exports = getScript;