I ran into the same problem.
First, make sure when you launch the app, you turn on nodeIntegration:
app.on('ready', _ => {
mainWindow = new BrowserWindow({
title: "My Electron App",
backgroundColor: '#FFF',
height: 800,
width: 1200,
center: true,
webPreferences: {
nodeIntegration: true // works on main window only
}
})
Then, reference this answer.
Playing with multiple options, both using require
and src=
methods work. See below with additional inline comments.
<html>
<head>
<!-- make sure you have the semicolon after the require -->
<!-- and make sure NOT to include the .js extension -->
<script>require('./renderer');</script>
<!-- make sure you include the extension -->
<script src="./renderer.js" ></script>
</head>
<body>
<!-- Put HTML first to avoid blocking -->
<!-- All same options as in head work here, but shouldn't block -->
<!-- In addition, async and defer might do something -->
<!-- async should run script asynchronously, and defer wait until DOM loads -->
<script src="./renderer.js" async></script>
<script src="./renderer.js" defer></script>
</body>
<!-- scripts put here seems intermittent which runs first -->
</html>
<!-- scripts put here seems intermittent which runs first -->
Some will block the HTML from loading until the script runs (I think if in the head
tag, no matter what), while others seemed random whether the HTML would load before the script ran. I tested with an alert box in my renderer.js
, which would block the window from showing the HTML rendering if it ran first.