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)
Everettss
source share