Preload a Universal Component On-Demand with the Preload Method

Tim Kindberg
InstructorTim Kindberg
Share this video with your friends

Social Share Links

Send Tweet

You can preload specific code bundles very easily with react-universal-component. You may know that a particular feature is likely to be loaded, so you can preload it. You still get the benefit of a fast initial render while also having other features loaded very soon after, ready to go.

Instructor: [00:01] Preloading a file that you think the user is likely to need is a good way to improve perceived performance. One way to accomplish that is potentially in a componented mount. We can call universal tab.preload. This is a static method available on the wrapped component.

[00:23] When you're using a dynamic import like this, dynamic means we're pulling a prop off of the function that we've passed to universal, and we're telling it to import a file based off that prop. If you're doing that, then you need to specify which file you'd like to load by passing the props in.

[00:44] We need to tell it which tab we want to load. Let's go ahead and preload foo. When I refresh, I should see home and foo both being loaded. If I change this to bar, save and refresh, now I'm seeing home and bar loaded. We could also preload both if we'd like, and now we have main, foo, and bar being loaded.

[01:14] Preloading a chunk on mount may or may not be a good thing. It might defeat the purpose of even chunking in the first place. If you're going to do this, you might as well just import it at the top, because you're loading it right away.

[01:29] Another good approach might be on mouse-over of a button. If someone's going to mouse over the foo button, we know they're likely to click it, because they've shown some interest. Let's go ahead and implement that. The way that's going to look is we're going to add onMouseEnter handler, and we're going to call the same static method on universal tab called preload. We're going to pass it the tab of foo to preload.

[02:11] Now, we'll go ahead and refresh here. We're not preloading anything on mount, and I'm interested...I'm moving around, and as soon as I hover over foo, it's loaded. Watch that again. As soon as I hover over foo down below, we're loading it. Now, when they click it, it's instantaneous.

[02:29] When we hover over bar, we're not preloading, so when we click bar, there's a little bit of a blink. If we were loading a larger file, it would take a lot longer.