All files / io getScript.ts

92.3% Statements 12/13
100% Branches 0/0
100% Functions 3/3
92.3% Lines 12/13

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                                    1x       2x 2x         2x 2x 2x             2x 2x 2x     2x 2x       1x  
/**
 * 加载 script 文件
 * @method getScript
 * @param {String} src script 地址
 * @param {Object} options 选项
 * @param {String} [options.charset='utf-8'] script 编码
 * @return {Promise<undefined>} 加载完成的回调
 * @example
 * import { getScript } from '@spore-ui/tskit';
 * getScript('https://sporeui.github.io/spore-kit/docs/js/test.js').then(() => {
 *   console.info('loaded');
 * });
 */
 
export interface TypeGetScriptOptions {
  charset?: string;
}
 
export function getScript(
  src: string,
  options?: TypeGetScriptOptions,
): Promise<void> {
  return new Promise((resolve) => {
    const conf: TypeGetScriptOptions = {
      charset: '',
      ...options,
    };
 
    const script = document.createElement('script');
    script.async = true;
    script.src = src;
 
    if (conf.charset) {
      script.charset = conf.charset;
    }
 
    // 自 IE9 开始,都支持 script.onload 了
    script.onload = () => {
      script.onload = null;
      resolve();
    };
 
    const head = document.querySelector('head');
    head.appendChild(script);
  });
}
 
export default getScript;