Skip to content

Instantly share code, notes, and snippets.

@nurullah
Created November 29, 2021 08:27
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 nurullah/7bcd0dd9a7dae140bd165057380661d2 to your computer and use it in GitHub Desktop.
Save nurullah/7bcd0dd9a7dae140bd165057380661d2 to your computer and use it in GitHub Desktop.
Embed React Build on All Sites
function EmbedReactBuild() {
this.url;
this.dependencies;
this.setURL = function(url) {
this.url = url;
}
this.setDependencies = function(dep) {
this.dependencies = dep;
return dep;
}
this._fetchDependencies = function() {
return fetch(this.url)
.then(res => res.json())
.then(res => res.entrypoints.map(e => Object.values(res.files).find(f => f.search(e) > 0)))
.then(dep => this.setDependencies(dep))
}
this._injectDependencies = function() {
this.dependencies.forEach(function(dep) {
const ext = dep.split(".").slice(-1)[0];
switch(ext) {
case 'css':
let link = document.createElement('link');
link.rel = "stylesheet";
link.href = dep;
document.head.appendChild(link);
break;
case 'js':
let script = document.createElement('script');
script.src = dep;
document.body.appendChild(script);
break;
default:
}
})
}
this.run = function() {
return this._fetchDependencies()
.then(() => this._injectDependencies());
}
}
<div id="root"></div>
<script src="./embed-react-build.js"></script>
<script>
const embed = new EmbedReactBuild()
embed.setURL("https://react-default.netlify.app/asset-manifest.json")
embed.run()
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment