Last active
July 5, 2022 07:02
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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