-
-
Save pgailloud/e70764ed8a72cebd178a874313e7627d to your computer and use it in GitHub Desktop.
native code to include a javascript / css file dynamically in a html document
This file contains hidden or 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
function include(src){ | |
return new Promise((resolve, reject) => { | |
var ext = src.split(/[\#\?]/)[0].split(".").pop().toLowerCase(); | |
var inc; | |
if (ext == "js") { | |
inc = document.createElement("script"); | |
inc.src = src; | |
inc.onerror = () => reject(); | |
inc.onload = inc.onreadystatechange = () => resolve(); | |
} | |
else { | |
inc = document.createElement("link"); | |
inc.rel = "stylesheet"; | |
inc.type = "text/css"; | |
inc.media = "screen"; | |
inc.href = src; | |
resolve(); | |
} | |
document.getElementsByTagName("head")[0].appendChild(inc); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Same thing but with promise instead of callbacks.