Lazy loading or “on demand” loading is a good way to optimize your site or application. This practice basically involves breaking up code at a logical breakpoint and then loading it after the user has done something that requires a new code block. This speeds up the initial load of the application and reduces its overall weight, since some blocks may never even load. Lazy loading is not unique to WebPack, but webPack supports lazy loading.

Take the official website for example:

Add the print.js file

webpack-demo
|- package.json
|- webpack.config.js
|- /dist
|- /src
  |- index.js
+ |- print.js
|- /node_modules
Copy the code

print.js

console.log('The print.js module has loaded! See the network tab in dev tools... ');
export default () => {
  console.log('Button Clicked: Here\'s "some text"!');
};
Copy the code

index.js

import _ from 'lodash';
function component() {
	const element = document.createElement('div');
	const button = document.createElement('button');
	const br = document.createElement('br');
	button.innerHTML = 'Click me and look at the console! ';
	element.innerHTML = _.join(['Hello'.'webpack'].' ');
	element.appendChild(br);
	element.appendChild(button);
	button.onclick = e => import(/* webpackChunkName: "print"* /'./print').then(module => {
            const print = module.default;
            print(a); });return element;
}
document.body.appendChild(component());
Copy the code

Packing results:

Asset Size Chunks Chunk Names bundle.js 559 KiB index [emitted] index index.html 182 bytes [emitted] print.bundle.js 643  bytesprint  [emitted]  print
Copy the code

Run index.html to view the Network, and only the bundle.js file is loaded. When you click the button, the print.bundle.js file is loaded. Lazy loading is implemented through the syntax of import.

If the print.bundle.js file is large, there will be a certain delay when we click the button, which will shorten the loading time of the first screen but affect the user experience. In this case, we can use Prefetch to solve this problem.

Prefetch tells the browser that this is a resource that might be used in the future.

Browsers typically fetch these resources in an idle state and then hold them in the HTTP cache for future requests. If there are multiple ‘pre-request prompts’, they are queued up for execution when the browser is idle. When the browser leaves idle and happens to be ‘pre-requesting’ a resource, the browser cancels any in-progress requests (while keeping part of the response data in the cache while continuing to use the Content-range field in the Header) and stops processing the ‘pre-requesting’ queue. Bottom line: Acquire resources when idle.

Using Prefetch is as simple as adding a magic comment to import:

Modify the index.js code

button.onclick = e => import(/* webpackChunkName: "print", webpackPrefetch: true* /'./print').then(module => {
      const print = module.default;
      print(a); });Copy the code

In addition to the bundle.js file, the browser finally loaded the print.bundle.js file, which was loaded by the browser in the idle state.

When you click the button, the browser reloads print.bundle.js again, this time from the browser cache, so it takes less time.

Preload indicates resources that may be required during the current navigation process.

The preload directive differs from prefetch in a number of ways:

The block of preload starts loading in parallel with the parent block. Prefetch starts after the parent block has finished loading.

Preload’s blocks have medium priority and can be downloaded immediately. Download the Prefetch block when the browser is idle.

The parent block should immediately request the preload block. Prefetch can be used at any time in the future.

Browser support varies.