There are many factors that affect the response speed of web pages, such as: the request content is too large, the number of HTTP requests is too large, the server itself takes too long to process the request, the JS script execution takes too long, the browser reflux redrawing, and so on. The speed of your page’s response is closely related to the user experience and directly affects whether users will continue to visit your site. Probably the most common problem for Vue projects is that the packaged files are too large and take too long to load. Server request processing takes too long, too long and js scripts are executed both with the quality of the code and the server configuration is too heavy, need according to the specific project and code optimization, today we only from the request number and packaging of the two layers of single file is too large to optimize web response speed (this applies to all front-end project).

1. The request is too large

After a project is packaged, it’s common to find that the vendors and APP files that have been packaged are especially large, with the vendors. The app.js file contains the logic code for each page in the project, and the Vendors. As the complexity of the project increases, so does the size of the file. In the case of limited bandwidth, downloading these two files often takes a long time.

Solution:

  1. Lazy route loading: Split code blocks

Vue supports asynchronous components, where you can use a Promise where the component is used, and the Promise eventually returns a component object through resolve. Webpack’s dynamic import approach allows code to be packaged in blocks and return a Promise(exactly what asynchronous components need). Using import in the routing configuration allows you to split each page component into separate code blocks and load the corresponding component when the route is accessed. This avoids packing everything in one chunk and thus “loading on demand”, greatly improving the response time. Import routing components as shown in the following figure:

  1. Introduced the CDN

Business code is constantly updated and iterated. In order for the browser to cache our static files for as long as possible, if we package the library code with the business code, the library code will be updated as the business code is updated, rather than using the browser cache for a long time. We wanted to take advantage of caching to reduce browser traffic and speed up user browser loading, so we split it up and packaged it separately. Generally, third party packages will have a script introduction scheme, you just need to ignore the third party package when packaging, and then add the corresponding import link on the template. First of all, no vue.config.js needs to be created in the project root directory as follows:

const cdn = {
    // Ignore packaged third-party libraries
    externals: {
      vue: 'Vue'."element-ui": "ELEMENT".'vue-router': 'VueRouter'.vuex: 'Vuex'.axios: 'axios'.moment: "moment".echarts: "echarts"
    },
  
    // Use the CDN mode
    js: [
      'https://cdn.bootcss.com/vue/2.6.10/vue.runtime.min.js'.'https://cdn.bootcss.com/vue-router/3.1.2/vue-router.min.js'.'https://cdn.bootcss.com/vuex/3.1.1/vuex.min.js'.'https://cdn.bootcss.com/axios/0.19.0/axios.min.js'.'https://cdn.bootcss.com/moment.js/2.24.0/moment.min.js'.'https://cdn.bootcss.com/echarts/3.7.1/echarts.min.js'."https://cdn.bootcdn.net/ajax/libs/element-ui/2.8.2/index.js",].css: ["https://unpkg.com/[email protected]/lib/theme-chalk/index.css"],}module.exports = {
    publicPath: '/CRM/dist/'.// publicPath: './',
    chainWebpack: config= > {
        config.plugin('html').tap(args= > {
            args[0].cdn = cdn
            return args
          })
          config.plugins.delete('prefetch')},// Packaging ignores third-party libraries
    configureWebpack: { 
        externals: cdn.externals
    },
}
Copy the code

Then add the corresponding location in the pulic/index.html template.

// Add a CDN variable, and then iterate through the template to add itThe < %for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.css) { %>
    <link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="stylesheet">
    <! -- <script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>" crossorigin="anonymous"></script> -->The < %} % >Copy the code

Another benefit of using a CDN is increased packaging speed.

  1. Compress request resources

Normally we deploy to a server that uses Nginx as a proxy server, and all requests are forwarded through Nginx. We can start gzip by configuring nginx.

server {
        gzip on;
        gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css;
}
Copy the code

After the configuration, each time the browser requests resources from the server, the server compresses the resources and returns them to the browser. After receiving the request, the browser decompresses the resources. This can greatly increase the download speed of static resources. The other thing is that every time the browser makes a request to the server, the server will perform a compression operation, and when the request volume is large, the compression operation will also affect the server response speed, so we can directly package the file as a compressed package. This does not require the server to package frequently:

Install dependency: compression-webpack-plugin

npm install compression-webpack-plugin --save-dev

Vue. Config. Js modified:

const CompressionPlugin = require('compression-webpack-plugin');
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\? . *)? $/i;
module.exports = {
    publicPath: '/'.productionSourceMap: false.configureWebpack: {... },chainWebpack: config= > {
        config.resolve.alias.set(The '@', resolve('src'));
        if (process.env.NODE_ENV === 'production') {
            config.plugin('compressionPlugin')
            .use(new CompressionPlugin({
                filename: '[path].gz[query]'.algorithm: 'gzip'.test: productionGzipExtensions,
                threshold: 10240.minRatio: 0.8.deleteOriginalAssets: true})); }}};Copy the code

Nginx configuration

server {
        gzip_static on;
        gzip on;
        gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css;
}
Copy the code

Too many HTTP requests

All things have a degree, which is what we call the extreme of the opposite. When we do on-demand loading, code splitting and packaging, as the project gets bigger and bigger and more and more modules, as the project gets packaged, we find that a lot of files are generated. For front-end performance, smaller files per file can mean more overhead to establish and close network connections, so a balance between the number of files and the size of individual files is often needed in front-end optimization practices. Here, we can use the plugin MinChunkSizePlugin provided by Webpack to keep the chunk size above the specified limit by merging chunks smaller than minChunkSize

Solution:

Vue. Config. Js configuration

module.exports = {
    publicPath: '/'.productionSourceMap: false.configureWebpack: {
        plugins: [
            new webpack.optimize.MinChunkSizePlugin({
              minChunkSize: 10000 // Minimum number of characters}})]},Copy the code

Through the above operations, we can control the packaged files in a reasonable size and quantity range, and then with the ngniX configuration, open gzip, basically can solve the problem of long wait time for the first loading of most vUE single-page applications.

Lu Xun once said that a comrade who does not give a thumbs up after reading the book is not a good comrade