創建 <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)
}
