Skip to content

Instantly share code, notes, and snippets.

@revolunet
Last active December 17, 2015 12:55
Show Gist options
  • Save revolunet/d37295d0d46c49002f71 to your computer and use it in GitHub Desktop.
Save revolunet/d37295d0d46c49002f71 to your computer and use it in GitHub Desktop.
SystemJS browser usage example [PoC]
/*
This example demonstrates how to load SystemJS and use npm deps from scratch in the browser
About SystemJS : https://github.com/systemjs/systemjs
- first loads SystemJS runtime from CDN with a script tag (same as if you add it with a script tag in the html)
- then loads some npm dependencies using SystemJS
- finally use react to add some component to the page
To see it in action : in Chrome devtools, choose the 'Snippet' tab, create a new one, paste this script then execute it.
*/
// basic external script loader
// used to load the base SystemJS runtime
function loadScript(src, cb) {
var tgt = document.querySelector('script[src="' + src + '"]')
if (!tgt) {
tgt = document.createElement('script');
tgt.src = src;
if (cb) {
tgt.onload = tgt.onerror = cb;
}
document.head.appendChild(tgt);
} else {
cb();
}
return tgt;
}
function loadDeps(...deps) {
return Promise.all(deps.map(dep => System.import(dep)));
}
// first load SystemJS runtime
loadScript('https://jspm.io/[email protected]', function() {
// then load multiple deps at once
loadDeps('npm:react', 'npm:react-dom', 'npm:react-countdown-clock')
.then(([React, ReactDOM, CountdownClock]) => {
// profit
// add a styled div to the current document
var tgt = document.createElement('div');
Object.assign(tgt.style, {
position: 'fixed',
top: 0,
left: 0,
width: '100%',
height: '100%',
opacity: 0.9,
textAlign: 'center',
paddingTop: '150px',
background: '#666',
zIndex: 999999
});
document.body.appendChild(tgt);
// create a react component instance
var clock = React.createElement(CountdownClock, {
seconds: 5,
color: "#000",
size: 200,
onComplete: () => {
alert('complete !')
}
});
// render the react component into our newly added div
ReactDOM.render(clock, tgt);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment