Performance optimization

1. Load vUE routes on demand

Package the routing page/trigger functionality as a separate file and load it only when you use it to reduce the burden of first-screen rendering. The more features a project has, the larger the package size, resulting in a slower rendering of the first screen. The following is used in the router:

The original:

import Vue from 'vue' import VueRouter from 'vue-router' import loading from '.. /views/loading.vue' import test from '.. /views/test.vue' Vue.use(VueRouter) const routes = [{ path: '*', redirect: '/loading' }, { path: '/loading', name: 'loading', component: loading }, { path: '/test', name: 'test', component: test, } ]; const router = new VueRouter({ routes })Copy the code

Change:

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const routes = [{
		path: '*',
		redirect: '/loading'
	},
	{
		path: '/loading',
		name: 'loading',
		component:  () => import('@/views/loading'),
	},
	{
		path: '/test',
		name: 'test',
		component: () => import('@/views/test'),
	}
        ];
const router = new VueRouter({
	routes
})
export default router

Copy the code

The difference is obvious in the number of JS and CSS packages printed after packaging

2. Vue partial code level optimization

(1) Reasonable use of V-if and V-show (2) V-for must add key, preferably a unique ID, avoid using index, V-for and V-IF should not be used at the same time (3) timer destruction. Destruction events can be executed within the beforeDestroy() life cycleCopy the code

2. Vue partial code level optimization

(1) Reasonable use of V-if and V-show (2) V-for must add key, preferably a unique ID, avoid using index, V-for and V-IF should not be used at the same time (3) timer destruction. Destruction events can be executed within the beforeDestroy() life cycleCopy the code

3. Anti-shake and throttling

Most of the mainstream UI frameworks for input and other change events have been done to prevent shaking, the main optimization is to write their own business logic related functions

Anti-vibration function:  function debounce(fn,delay = 500){ let timer = null return function(){ if(timer) { clearTimeout(timer) } timer = setTimeout(()=>{ fn.apply(this,arguments) timer = null },delay) } }Copy the code

The core logic is: when triggered continuously, the last one is automatically cleared by setTimeout, and then a new one is assigned. The disadvantage is that it needs to wait for the event of a delay device

Throttle function:  function throttle(fn,delay = 500) { let timer = null return function() { if(timer) { return } timer = setTimeout(()=>{ fn.apply(this,arguments) timer = null },delay) } }Copy the code