创建 <script> 外部引入 js 文件

参考保利威视文档:https://dev.polyv.net/2020/videoproduct/v-player-sdk/v-player-sdk-web/integration/

 

如果需要在页面中引入外部 js 文件,但是由于某种原因不能直接在根页面 <script> 引入,可以封装一个方法,采用 appendChild 插入节点。

react 实现方法:

 loadScript(src) {
    const headElement = document.head || document.getElementsByTagName('head')[0];
    const _importedScript = {};

    return new Promise((resolve, reject) => {
      if (src in _importedScript) {
        resolve();
        return;
      }
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.onerror = err => {
        headElement.removeChild(script);
        reject(new URIError(`The Script ${src} is no accessible.`));
      }
      script.onload = () => {
        _importedScript[src] = true;
        resolve();
      }
      headElement.appendChild(script);
      script.src = src;
    })
  }
loadScript('https://xxx/xxxxx.js')

 

posted @ 2021-04-13 17:28  Freya~  阅读(1047)  评论(0)    收藏  举报