Code division / preloading of contents while viewing by the user?

Using tools such as Webpack, we can enable code separation and just download our application code asynchronously if necessary.

An example in the context of a reactive application with a reactive router.

Load initial page. -> go to new route ---> webpack loads in the component file required asynchronous. 

Webpack waits until the code is needed to initiate the request.

My question is that after loading the base code of the application, can we start downloading the rest of the code, even before the user starts the transition to a new route?

My opinion is that the user will not be able to download the downloadable webpack package.

 -> Load initial page --> user sitting idle or browsing on home page ----> Start loading application code for rest of the application ---> user goes to new route (faster UX because code has already download in the background) 

Hope this makes sense

+7
javascript webpack
source share
1 answer

Yes, you can achieve this . I will show one of the possible solutions.

First create a backgroundLoader for the order of the required fragments:

 const queue = []; const delay = 1000; let isWaiting = false; function requestLoad() { if (isWaiting) { return; } if (!queue.length) { return; } const loader = queue.pop(); isWaiting = true; loader(() => { setTimeout(() => { isWaiting = false; requestLoad(); }, delay) }); } export default (loader) => { queue.push(loader); requestLoad(); } 

This function will load your fragments in the background with a 1 second delay (you can configure it, for example, start calling the queue after, for example, 5 seconds or shuffle an array of pieces).

Then you must register the require.ensure function in the backgroundLoader standby mode:

 import render from './render'; // not relevant in this example import backgroundLoader from './backgroundLoader'; let lightTheme = (cb) => { require.ensure([], () => { cb(require('./themeA.css')); }, 'light'); } let darkTheme = (cb) => { require.ensure([], () => { cb(require('./themeB.css')); }, 'dark'); } let pinkTheme = (cb) => { require.ensure([], () => { cb(require('./themeC.css')); }, 'pink'); } backgroundLoader(lightTheme); backgroundLoader(darkTheme); backgroundLoader(pinkTheme); export default (themeName) => { // router simulation switch(themeName) { case 'light': lightTheme(render); break; case 'dark': darkTheme(render); break; case 'pink': pinkTheme(render); break; } }; 

As soon as you need your piece in the switch , you pass the render function containing the resolution function. In backgroundLoader this function will be empty, which will lead to the loading of a piece in the head your application.

You can see the full code for this example on WebpackBin (you can check the network to see how the pieces load in the background)

+3
source share

All Articles