Skip to content

Instantly share code, notes, and snippets.

@zhangzhibin
Last active Sep 24, 2021
Embed
What would you like to do?
Dynamically load a js script and set parameters
// JavaScript 根据需要动态加载脚本并设置参数
// refer to https://xmanyou.com/javascript-dynamically-load-script-and-set-parameters/
async function loadJsAsync(src:string, async:boolean=false, options?:any) {
return new Promise<void>((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.async = async;
if(options) {
for(const key in options) {
// script[key] = options[key];
script.setAttribute(key, options[key]);
}
}
let onload = () => {
script.removeEventListener('load', onload);
// resolve in onload callback for async loading
if(!async) {
resolve();
}
};
script.addEventListener('load', onload);
script.addEventListener('error', (err) => {
console.error(err);
reject(new Error(`Failed to load ${src}`));
});
// document.head.appendChild(script);
( document.getElementsByTagName("head")[0] || document.documentElement ).appendChild( script );
// resolve immediately for sync loading
if(async){
resolve();
}
});
}
export { loadJsAsync }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment