Skip to content

Instantly share code, notes, and snippets.

@teknixstuff
Last active May 12, 2022 01:32
Show Gist options
  • Save teknixstuff/320485a455e5a6fb9c2f4467a5374b4c to your computer and use it in GitHub Desktop.
Save teknixstuff/320485a455e5a6fb9c2f4467a5374b4c to your computer and use it in GitHub Desktop.
Require for client-side JS

Example

<script src="https://gist.githubusercontent.com/teknixstuff/320485a455e5a6fb9c2f4467a5374b4c/raw/require.js">
<script>
require('github:medialize/sass.js/dist/sass.sync.js');
require('npm:jquery@3');
</script>
async function require(script) {
const location = script.split(':',2);
let pkgurk;
if (location.length != 2) {
throw new Error('Package location couldn't be parsed.');
}
switch(location[0]) {
case 'url':
pkgurl = location[1];
break;
case 'unpkg':
pkgurl = '//unpkg.com/' + location[1];
break;
case 'jsdelivr':
case 'osscdn':
pkgurl = '//cdn.jsdelivr.net/' + location[1];
break;
case 'jsdelivr-npm':
case 'osscdn-npm':
case 'npm':
pkgurl = '//cdn.jsdelivr.net/npm/' + location[1];
break;
case 'jsdelivr-gh':
case 'osscdn-gh':
case 'jsdelivr-github':
case 'osscdn-github':
case 'gh':
case 'github':
pkgurl = '//cdn.jsdelivr.net/gh/' + location[1];
break;
case 'jsdelivr-wp':
case 'osscdn-wp':
case 'jsdelivr-wordpress':
case 'osscdn-wordpress':
case 'wp':
case 'wordpress':
pkgurl = '//cdn.jsdelivr.net/wp/' + location[1];
break;
default:
throw new Error('Bad package location type.');
break;
}
await fetch(pkgurl,{credentials:'omit',cache:'default',mode:'cors'}).then(eval);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment