Skip to content

Instantly share code, notes, and snippets.

@yussan
Last active October 6, 2021 13:21
Show Gist options
  • Save yussan/c050ebbda71c459fc5c111d5b402eded to your computer and use it in GitHub Desktop.
Save yussan/c050ebbda71c459fc5c111d5b402eded to your computer and use it in GitHub Desktop.
Async load external JS using JS
export default function loadJS(src: string, args: any) {
if(!isScriptLoaded(src)) {
const s: HTMLElement | null = document.createElement('script')
s.setAttribute('src', src)
if(args.id) s.setAttribute('id', args.id)
if(args.cb)
s.onload = args.cb()
document.body.appendChild(s)
}
}
function isScriptLoaded(src: string) {
const scripts = document.getElementsByTagName('script')
// is script available
for (let i = scripts.length; i--;) {
if (scripts[i].src == src) return true
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment