


Introduction to home screen optimization of Vue SPA single-page application
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;
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)
- Match the MIME type for compression, (whether specified or not) the "text/html" type will always be compressed
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());
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
in the project, Import on demand: First install babel-plugin-component:
npm install babel-plugin-component -D
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 retrycnpmThis is
’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)
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('get', url, true); xhr.setRequestHeader('content-type', 'application/json'); 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('post', url, true); xhr.setRequestHeader('content-type', 'application/json'); 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;
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(['./Foo.vue'], () => { resolve(require('./Foo.vue')) }) } /* 另一种写法 */ const Foo = resolve => require(['./Foo.vue'], resolve);
No need to change any routing configuration, use Foo as before:
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo } ] })4. Webpack2 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.
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).
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.
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
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!

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools
