Skip to content

Instantly share code, notes, and snippets.

@brrd
Last active July 5, 2022 07:02
Show Gist options
  • Save brrd/d3d337e45509541d1b95d483573493a1 to your computer and use it in GitHub Desktop.
Save brrd/d3d337e45509541d1b95d483573493a1 to your computer and use it in GitHub Desktop.
Electron: dynamic include JS and/or CSS from a dependency in renderer process
// Install 'module-name' as a dependency, then:
function init () {
return new Promise ((resolve, reject) => {
const injectScript = (src, callback) => {
const script = document.createElement('script');
document.head.appendChild(script);
script.onload = callback;
script.src = src;
};
const injectStylesheet = (src) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = src;
document.head.appendChild(link);
};
const cssPath = require.resolve("module-name/dist/styles.css");
const jsPath = require.resolve("module-name/dist/module.js");
injectStylesheet(cssPath);
injectScript(jsPath, resolve);
});
}
module.exports = () => {
init().then(() => {
// Do stuff...
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment