Last active
October 6, 2021 13:21
-
-
Save yussan/c050ebbda71c459fc5c111d5b402eded to your computer and use it in GitHub Desktop.
Async load external JS using JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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