原生 js 创建 DOM 节点并插入页面,几个记录

 

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

需求:想要在页面中引入外部 js 文件,但是因各种原因不能直接在根页面引入 <script src="//xxx/xxxxx.js"></script>,可以封装一个方法,采用 appendChild 插入节点。

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')

 借鉴:保利威云点播Web播放器官方文档,react 写法的部分代码:https://dev.polyv.net/2020/videoproduct/v-player-sdk/v-player-sdk-web/integration/

 

 

navigation.ts

export function openExternalUrl(url: string, target?: string) {
  const a = document.createElement('a')
  a.setAttribute('href', url)
  a.setAttribute('target', target || '_blank')
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a as HTMLElement)
}

  

 

posted @ 2020-11-05 15:15  Jaye8584  阅读(1132)  评论(0编辑  收藏  举报