All files / io loadSdk.js

93.55% Statements 29/31
83.33% Branches 10/12
100% Functions 3/3
93.55% Lines 29/31

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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 761x 1x 1x   1x 1x                                   1x 4x             4x 4x 4x 1x 1x           4x 4x 1x   3x 1x     2x 2x 1x     1x     1x 1x         1x 1x 1x       1x   1x     1x  
var $assign = require('../obj/assign');
var $get = require('../obj/get');
var $getScript = require('./getScript');
 
var propName = 'SPORE_SDK_PROMISE';
var cache = null;
 
/**
 * sdk 加载统一封装
 * - 多次调用不会发起重复请求
 * @method io/loadSdk
 * @param {Object} options 选项
 * @param {String} options.name sdk 全局变量名称
 * @param {String} options.url script 地址
 * @param {String} [options.charset='utf-8'] script 编码
 * @param {Function} [options.onLoad] script 加载完成的回调函数
 * @example
 * var $loadSdk = require('@spore-ui/kit/packages/io/loadSdk');
 * $loadSdk({
 *   name: 'TencentCaptcha',
 *   url: 'https://ssl.captcha.qq.com/TCaptcha.js'
 * }).then(TencentCaptcha => {})
 */
var loadSdk = function (options) {
  var conf = $assign({
    name: '',
    url: '',
    charset: 'utf-8',
    wtop: window,
  }, options);
 
  Eif (typeof conf.wtop !== 'undefined') {
    cache = conf.wtop[propName];
    if (!cache) {
      cache = {};
      conf.wtop[propName] = cache;
    }
  } else {
    cache = {};
  }
 
  var name = conf.name;
  if (!name) {
    return Promise.reject(new Error('Require parameter: options.name'));
  }
  if (!conf.url) {
    return Promise.reject(new Error('Require parameter: options.url'));
  }
 
  var pm = cache[name];
  if (pm) {
    Iif (pm.sdk) {
      return Promise.resolve(pm.sdk);
    }
    return pm;
  }
 
  pm = new Promise(function (resolve) {
    $getScript({
      src: conf.url,
      charset: conf.charset,
      wtop: conf.wtop,
      onLoad: function () {
        var sdk = $get(conf.wtop, name);
        pm.sdk = sdk;
        resolve(sdk);
      },
    });
  });
  cache[name] = pm;
 
  return pm;
};
 
module.exports = loadSdk;