After the launch of the development project with VUE, I found that the loading speed of the home page was very slow. If the project was relatively large, there might even be a wait of more than 10 seconds. The user experience is very poor. Imagine if you are going to buy a pair of AJ, log in to the home page of a treasure and wait for a full 5s, then you will definitely choose Xinduoduo.

Take our company’s project as an example, after entering the url, there will be a blank page for more than ten seconds. If it is acceptable for the background management system, the nested H5 is facing c-end users, which is definitely unacceptable for the product.

After careful analysis, the main reason is that the packaged app.js is too large, and some plug-in installation packages we quoted are slow to load. We searched many solutions to solve the slow loading on the Internet, and the optimized time is more than 2 seconds on the H5 page of the mobile terminal and more than 5 seconds on the background management system.

1. Lazy route loading

{
    path: '/chinaWine',
    name: 'chinaWine',
    component: resolve => require(['./views/chinaWine'], resolve)
},
Copy the code

This method splits the package into multiple JS files that were originally packaged into one app.js file, which reduces the size of the individual file but not the size of the entire JS folder.

In this way, you can load on demand, loading only the JS files of a single page.

2. Remove the map file from the package file

The packaged app.js is too large, plus some generated map files. Remove the extra map files first,

Find the index.js file in config folder and change productionSourceMap to false in build

3. CDN introduces third-party libraries

In project development, we will use many third-party libraries. If we can introduce them as needed, we can only introduce the components we need to reduce the space occupied.

However, some components cannot be imported on demand. We can use CDN external loading, import components from CDN in index. HTML, remove component import from other pages, modify webpack.base.config.js, and add this component to externals. This is to avoid an error when a component is not found at compile time.

4. Gzip packaging

Gizp compression is an HTTP request optimization that improves load speed by reducing file size.

HTML, JS, CSS files and even JSON data can be compressed with it, reducing the size by more than 60%.

1. NPM I -D Compression -webpack-plugin

2. Configure it in vue.config.js

const CompressionPlugin = require('compression-webpack-plugin')

configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
        return {
            plugins: [new CompressionPlugin({
                test: /\.js$|\.html$|\.css/,
                threshold: 10240,
                deleteOriginalAssets: false
            })]
        }
    }
}
Copy the code

3. Configure in NGINX

http { gzip on; gzip_min_length 1k; gzip_buffers 4 8k; Gzip_http_version 1.0; gzip_comp_level 8; gzip_proxied any; gzip_types application/javascript text/css image/gif; gzip_vary on; gzip_disable "MSIE [1-6]\."; # The following configuration is omitted... }Copy the code

Nginx -s reload: Modify the configuration and reload it to take effect

5, the ultimate trick, pre-rendering

In fact, it is no problem to optimize the above to within 5 seconds, but if we have more than 100 front-end pages, it may still be a little slow.

We did so much above, are based on js after the rendering, if you want to go faster, there are two solutions, one is SSR is server rendering, one is pre-rendering.

Pre-render generates a static page of the home page before js loading, which will not make you wait, static page performance needless to say, swish.

Prerendering relies on the prerender-spa-plugin, which is very simple to use, but there are so many bugs that you can get an error if you don’t respect the prerender-spa-plugin:

Install prerender-spa-plugin –save-dev

It is recommended to use taobao mirror CNPM, because the NPM installation often fails, blood and tears, poured in the morning

2, the vue. Config. Js

const path = require('path'); const PrerenderSPAPlugin = require('prerender-spa-plugin'); const Renderer = PrerenderSPAPlugin.PuppeteerRenderer; Under the plugins, find the plugins object and add it directly to the PrerenderSPAPlugin({// require - to WebPack- export the application's path to pre-render. StaticDir: path.join(__dirname, 'dist'), // Required, route to render. Renderer: new renderer ({inject: {foo: 'bar'}, headless: False, // Display browser window at render time. Useful for debugging. // Wait for rendering until the specified element is detected. / / use the entrance of the project, for example, ` document. The dispatchEvent (new Event (' custom - render - trigger) ` renderAfterDocumentEvent: 'render - Event'})})Copy the code

3, the router. Js

You need to set vue's router mode to History modeCopy the code

4, the main js

Add an event to Create Vue instance Mounted that corresponds to renderAfterDocumentEvent in the instance PrerenderSPAPlugin.

mounted () {
    document.dispatchEvent(new Event('render-event'))
 },
 
Copy the code

This is the basic configuration of pre-rendering, NPM run build, if you want to pre-render folder more folder, then congratulations, success! If the project uses nginx as a proxy, nginx also needs to do some configuration, specifically:

location = / {
  try_files /home/index.html /index.html;
}

location / {
  try_files $uri $uri/ /index.html;
}
Copy the code

Specific according to their own needs to render route with their own

Although it took one day to realize the pre-rendering, because the project used hash routing before, the pre-rendering mode needed to be changed to history mode and the login address needed to be modified. Our company used thousands of terminal merchants, so the plan was aborted. But really fast, suitable for their own use of the background, new projects.