Home Web Front-end JS Tutorial Introduction to home screen optimization of Vue SPA single-page application

Introduction to home screen optimization of Vue SPA single-page application

Jun 28, 2018 pm 03:43 PM
vue

This article mainly introduces the first screen optimization practice of Vue SPA single-page application. The content is quite good. I will share it with you now and give it as a reference.

1. Code compression (gzip)

If you are using nginx server, please modify the configuration file (other web servers are similar): sudo nano /etc/nginx/nginx.conf

Add in Gzip Settings:

gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_comp_level 5;
gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php;
Copy after login
  • gzip

    • Turn on or off the gzip module, use on here to indicate startup

  • gzip_min_length

    • Set to allow compression The minimum number of bytes in the page. The default value is 0, which compresses the page regardless of its size.

  • gzip_buffers

    • Set the system to obtain several units of cache for storing the gzip compression result data stream. 4 16k means applying for memory in units of 16k and 4 times the original data size in units of 16k

  • gzip_comp_level

    • ##Compression ratio, the minimum compression ratio of 1 is the fastest, and the compression ratio of 9 is the maximum but the slowest processing (fast transmission but consumes more CPU)

    ##gzip_types
    • Match the MIME type for compression, (whether specified or not) the "text/html" type will always be compressed
    I do this Configuration, a file that needs to be downloaded on the homepage is compressed from 716KB to 246KB. Optimization ratio 66%.

If you do not enable gzip on the server side, you can also enable compression of the front-end and back-end codes.

If your back-end uses the Express.js framework to provide Web services, Then you can use compression middleware for gzip compression.

var compression = require('compression');
var express = require('express');
var app = express();
app.use(compression());
Copy after login

If your front-end is a project generated with vue-cli, then code compression has been enabled in the Webpack configuration file (production environment).

2. Import external files on demand||Invent your own wheel without external files


If you use

Element

in the project, Import on demand: First install babel-plugin-component:

npm install babel-plugin-component -D
Copy after login

It allows us to introduce only the components we need to reduce the size of the project.

PS: If an error is reported at this time:

Error: post install error, please remove node_modules before retry


This is
cnpm

’s fault . The reason is unknown. The solution is to use npm to install this module. (I tried removing the node_modules file, but the error remained)

If you use an Ajax-related library, such as vue-resource/axios

Remove it and do it yourself Implement an Ajax library.

For example, my project only involves

get, post

, then vue-resource/axios is very unnecessary for me. So I encapsulated a library (supports Promise, does not support IE) and uses it as a plug-in in Vue:

/* xhr.js */
class XHR {
 get(url) {
  return new Promise((resolve, reject) => {
   const xhr = new XMLHttpRequest();
   xhr.onreadystatechange = () => {
    if (xhr.readyState === 4) {
     if (xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304)) {
      if (xhr.responseText) {
       resolve(JSON.parse(xhr.responseText));
      } else {
       resolve(xhr.responseText);
      }
     } else {
      reject(`XHR unsuccessful:${xhr.status}`);
     }
    }
   };
   xhr.open(&#39;get&#39;, url, true);
   xhr.setRequestHeader(&#39;content-type&#39;, &#39;application/json&#39;);
   xhr.send(null);
  });
 }

 post(url, data) {
  return new Promise((resolve, reject) => {
   const xhr = new XMLHttpRequest();
   xhr.onreadystatechange = () => {
    if (xhr.readyState === 4) {
     if (xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304)) {
      resolve(JSON.parse(xhr.responseText));
     } else {
      reject(`XHR unsuccessful:${xhr.status}`);
     }
    }
   };
   xhr.open(&#39;post&#39;, url, true);
   xhr.setRequestHeader(&#39;content-type&#39;, &#39;application/json&#39;);
   xhr.send(JSON.stringify(data));
  });
 }
}

/* Vue插件要求提供install方法:https://cn.vuejs.org/v2/guide/plugins.html */
XHR.install = (Vue) => {
 Vue.prototype.$get = new XHR().get;
 Vue.prototype.$post = new XHR().post;
};

export default XHR;
Copy after login

This method can generally reduce the file size by dozens of KB. For example, vue-resource is 35KB, and my xhr.js is only 1.9KB.

3. Code Splitting/Code Splitting


As the name suggests, it means dividing the code into chunks and loading them on demand. In this way, if there are blocks that are not needed on the first screen, there is no need to load them.

It may be more useful for large projects, because the files required for the homepage in my project are basically the same as those required for other pages, so code blocking is not necessary for my project.

4. Lazy loading of routing components


When packaging and building an application, the Javascript package will become very large, affecting page loading. If we can split the components corresponding to different routes into different code blocks, and then load the corresponding components when the route is accessed, it will be more efficient.

Combine Vue's asynchronous components and Webpack's code splitting feature , you can easily implement lazy loading of routing components.

What we have to do is to define the component corresponding to the route as an asynchronous component:

const Foo = resolve => {
 /* require.ensure 是 Webpack 的特殊语法,用来设置 code-split point
 (代码分块)*/
 require.ensure([&#39;./Foo.vue&#39;], () => {
 resolve(require(&#39;./Foo.vue&#39;))
 })
}
/* 另一种写法 */
const Foo = resolve => require([&#39;./Foo.vue&#39;], resolve);
Copy after login

No need to change any routing configuration, use Foo as before:

const router = new VueRouter({
 routes: [
 { path: &#39;/foo&#39;, component: Foo }
 ]
})
Copy after login

4. Webpack2 Tree-shaking


Tree-shaking

is used to eliminate unused code. Generally, tree-shaking is not used in small personal projects. Because you won't write unused code. Large-scale projects may try to use it.

5. Reduce unnecessary data in XHR.


For example, in my project, the homepage only needs blog Title, id and Tags. Time and Content are no longer needed, and Content is usually very large (generally about 10KB per article).

6. SSR (Server Side Render/Server Side Rendering)


This is a bit difficult to do. But the effect seems to be quite good. I took a brief look at the Vue documentation before and planned to do it if I need it in the future.

7. I won’t go into details about other things such as lazy loading of images. It’s common sense that front-end developers should have.


The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

related suggestion:

How to use vue's transition to complete the sliding transition

Usage of $refs in Vue

How to install Mint-UI in vue project

The above is the detailed content of Introduction to home screen optimization of Vue SPA single-page application. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

Vue realizes marquee/text scrolling effect Vue realizes marquee/text scrolling effect Apr 07, 2025 pm 10:51 PM

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with &lt;div&gt;. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

See all articles