Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Load CSS in a Electron BrowserWindow

    Cameron NokesCameron Nokes

    In this lesson we'll learn how to load CSS in an Electron BrowserWindow, which is just like loading CSS into the browser. We’ll also use the ready-to-show event to only display our BrowserWindow when its rendering is complete.

    electronElectron
    ^3.0.7
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 We've already set up our main process JavaScript. We're creating a browser window, and we're loading an HTML file into it, index.html. Additionally, in that index.html file, we're requiring renderer.js, which is printing out the Electron version to the screen.

    00:18 What we want to do here is add a CSS file to style our content. Loading CSS in a web page in Electron is the exact same as loading CSS in the browser. We're going to add our link element here, set the rel attribute to stylesheet, and the href to style.css.

    00:37 Let's create our style.css. We're just going to do some simple styling here. What this does is it centers everything. We give it a nice color and a sans serif font. Let's run our NPM start script to see what it looks like.

    01:01 Great. We can see the CSS is getting loaded on the page, but in order for it to feel more like a native app, let's make it so that we don't even show the window until the DOM has been completely rendered. We're loading files locally, so there's not any real network latency to speak of, but it still takes some time for Chromium to parse and render the DOM.

    01:19 In order to do that, we're going to jump back into our main process JavaScript. Let's go to our main.js here. In our browser window constructor call, we're going to pass an option for show equals false. Now, if we ran our application at this point, the browser window wouldn't even show up.

    01:38 Let's add a ready to show event handler. In here, we'll tell our main window to show. The ready to show event is like the DOM ready event. It is emitted when a renderer process is done drawing for the first time.

    01:56 If we show our browser window when it's ready to show, we can be sure that the user will see a fully rendered page without any flickering or flashes of unstyled content. Let's run it with our NPM start script.

    02:08 We can see that the window showed up just a tiny bit slower than before, but when it did show up, it was completely ready to show, and there was no flickering.

    Discuss

    Discuss