Skip to content

Instantly share code, notes, and snippets.

@darkcris1
Last active February 27, 2021 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darkcris1/dc1d5490ae2436771405ce02e5563bac to your computer and use it in GitHub Desktop.
Save darkcris1/dc1d5490ae2436771405ce02e5563bac to your computer and use it in GitHub Desktop.
Install a npm package with udm type only in the browser
/**
* This will return true if the value is some of the items
* @param {string} pkgName
* @param {string} functionName
* @param {function} callback
*/
function npm(pkgName,functionName,callback){
const http = new XMLHttpRequest();
const url = "https://unpkg.com/" + pkgName;
const global = window || this;
http.open("GET",url);
http.send();
http.onreadystatechange = function(res){
if (http.readyState === XMLHttpRequest.DONE) {
const status = http.status;
switch (status) {
case 200:
new Function(http.responseText)()
const fn = global[functionName];
if (typeof fn !== "function") throw new Error("function name must be valid");
callback(fn);
break;
case 404:
throw new Error("Package Not Found");
default:
throw new Error("Network Error");
}
}
}
}
// Example
npm("sweetalert","swal",(swal)=>{
swal("asdasd")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment