Skip to content

Instantly share code, notes, and snippets.

@pgailloud
Forked from adrienjoly/include.js
Created January 7, 2019 16:00
Show Gist options
  • Select an option

  • Save pgailloud/e70764ed8a72cebd178a874313e7627d to your computer and use it in GitHub Desktop.

Select an option

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
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);
});
}
@pgailloud
Copy link
Copy Markdown
Author

Same thing but with promise instead of callbacks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment