Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Vue project first screen performance optimization component method tutorial

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains the "Vue project first screen performance optimization component method tutorial", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn the "Vue project first screen performance optimization component method tutorial"!

Vue first screen performance optimization component

Simple implementation of a Vue first screen performance optimization component, modern browsers provide a lot of new interfaces, without considering IE compatibility, these interfaces can greatly reduce the workload of writing code and do some performance optimization work, of course, in order to consider IE, we can also cover it when encapsulating components, the first screen performance optimization component of this article mainly uses IntersectionObserver and requestIdleCallback interfaces.

Description

Consider the first screen scenario first. When the first screen is mainly used for display, more resources, such as images, are usually loaded. If we do not want to load all the resources when the user opens it, but we want the user to load the components when he scrolls to the relevant location, we can choose the IntersectionObserver interface at this time. Of course, we can also use the onscroll event to do a listening, but the performance may be poor. There are also some components that we want him to load, but we don't want him to load synchronously when initializing the page, so we can use asynchronous methods such as Promise and setTimeout, but if we want to lower the priority of loading this component, we can consider the requestIdleCallback interface, the related code in the vue--first-screen-optimization branch of https://github.com/WindrunnerMax/webpack-simple-environment.

IntersectionObserver

The IntersectionObserver interface, which belongs to IntersectionObserver API, provides a way to asynchronously observe the cross state between the target element and its ancestor element or the top-level document window viewport. The ancestor element and the window viewport is called the root root, that is to say, the IntersectionObserver API, which can automatically observe whether the element is visible. Because the essence of the visible visible is that the target element and the viewport produce an intersection, this API is called the cross viewer, compatibility https://caniuse.com/?search=IntersectionObserver.

Const io = new IntersectionObserver (callback, option); / / start watching io.observe (document.getElementById ("example")); / / stop observing io.unobserve (element); / / close observer io.disconnect ()

The parameter callback, after creating a new IntersectionObserver object, executes the specified callback function when it listens that the visible portion of the target element passes through one or more threshold thresholds.

The second parameter of the parameter option,IntersectionObserver constructor is a configuration object that sets the following properties:

The threshold attribute determines when to trigger the callback function. It is an array with a threshold value for each member. The default is [0], that is, the callback function is triggered when the cross-ratio intersectionRatio reaches 0. Users can customize the array, for example, [0,0.25,0.5,0.75,1] means that the callback function will be triggered when the target elements are 0,25,50,75,100% visible.

The root attribute specifies the container node where the target element is located, that is, the root element. The target element scrolls not only with the window, but also in the container, such as in the iframe window, so you need to set the root attribute. Note that the container element must be the ancestor node of the target element.

The rootMargin attribute defines the margin of the root element, which is used to expand or reduce the size of the rectangle rootBounds, thereby affecting the size of the intersectionRect cross region. It uses CSS definition methods, such as 10px 20px 30px 40px, to represent the values in the four directions top, right, bottom, and left.

The property IntersectionObserver.root is read-only, and the specific ancestor element element of the listening object. If no value is passed in or the value is null, the window of the top-level document is used by default.

The attribute IntersectionObserver.rootMargin is read-only. The rectangular offset added to the root root bounding box bounding box when calculating the crossover can effectively narrow or expand the decision range of the root to meet the calculation needs. The value returned by this property may be different from the value specified when calling the constructor, so you may need to change the value to match the internal requirements. All offsets can be expressed in pixels pixel, px or percentage percentage,%. The default value is 0px 0px 0px 0px.

The property IntersectionObserver.thresholds is read-only, a list of thresholds, sorted in ascending order, each threshold in the list is the ratio of the crossing area of the listening object to the boundary area, when any threshold of the listening object is crossed, a notification Notification is generated, and if the constructor does not pass in a value, the default value is 0.

The method IntersectionObserver.disconnect () causes the IntersectionObserver object to stop listening.

The method IntersectionObserver.observe () causes IntersectionObserver to start listening on a target element.

The method IntersectionObserver.takeRecords () returns an array of IntersectionObserverEntry objects for all observation targets.

Method IntersectionObserver.unobserve (), which causes IntersectionObserver to stop listening on specific target elements.

In addition, when the callback function is executed, an IntersectionObserverEntry object parameter is passed, which provides the following information.

Time: the time when visibility changes, which is a high-precision timestamp in milliseconds.

Target: the target element being observed is a DOM node object.

RootBounds: the information about the rectangular area of the root element, which is the return value of the getBoundingClientRect method, or returns null if there is no root element, which scrolls directly relative to the viewport.

BoundingClientRect: information about the rectangular area of the target element.

IntersectionRect: information about the intersection of the target element with the viewport or root element.

IntersectionRatio: the visible ratio of the target element, that is, the ratio of intersectionRect to boundingClientRect, is 1 when it is fully visible, and less than or equal to 0 when it is completely invisible.

{time: 3893.92, rootBounds: ClientRect {bottom: 920, height: 1024, left: 0, right: 1024, top: 0, width: 920}, boundingClientRect: ClientRect {/ /...}, intersectionRect: ClientRect {/ /...}, intersectionRatio: 0.54, target: element} requestIdleCallback

The requestIdleCallback method can accept a function that will be called during the browser's idle time, which enables the developer to perform background and low-priority work on the main event loop without affecting the delay of critical events, such as animation and input response. The function is generally executed in the first-in-first-call order. If the callback function specifies the execution timeout timeout, it is possible to disrupt the execution order in order to execute the function before the timeout. Compatibility https://caniuse.com/?search=requestIdleCallback.

Const handle = window.requestIdleCallback (callback [, options])

The requestIdleCallback method returns an ID, which can be passed into the window.cancelIdleCallback () method to end the callback.

The parameter callback, a reference to a function that will be called when the event loop is idle, receives an argument called IdleDeadline, which gets the current idle time and the state of whether the callback has been executed before the timeout.

The parameter options is optional, including optional configuration parameters, with the following attributes:

Timeout: if timeout is specified and there is a positive value, and the callback has not been called after timeout milliseconds, the callback task will be queued in the event loop, even if doing so may have a negative impact on performance.

Realize

In fact, the main thing to write a component is to figure out how to use these two main API. Focus on IntersectionObserver first, because considering the need to use dynamic components, we need to use the form of asynchronously loaded component () = > import ("component") when passing values to it. When monitoring, you can consider destroying the listener after loading, or destroying it after leaving the visual area, which is mainly a matter of strategy. Intersection Observer must be disconnect when the page is destroyed to prevent memory leaks. Using requestIdleCallback is relatively simple, as long as you execute the callback function, which is also similar to the case of asynchronous processing like Promise.resolve (). Then.

Here is the simple implementation logic. Usually, the use of observer is to first use a div to occupy space, and then monitor its occupying container in observer. When the container is in the view area, the relevant components are loaded and the relevant code is installed in the vue--first-screen-optimization branch of https://github.com/WindrunnerMax/webpack-simple-environment. Please try to install it with yarn. You can use yarn.lock files to lock the version to avoid dependency problems. After running with npm run dev, you can see the order of the creation of the four lazy loading components created in Console, in which the observer lazy loading of A needs to wait until the loading page rendering is completed, and then load it in the visible area, which can be seen directly on the first screen, while the lazy loading of D needs to slide the scroll bar to the external container of D to appear in the view. That is, D components will not be loaded as long as you don't scroll to the bottom, and you can also pass attrs and listeners to lazily loaded components through component-params and component-events, similar to $attrs and $listeners, so lazily loaded components have been easily implemented.

1 2 3 4 5 import {Component, Vue} from "vue-property-decorator"; import LazyLoad from ". / components/lazy-load/lazy-load.vue" @ Component ({components: {LazyLoad},}) export default class App extends Vue {protected Example = () = > import (". / components/example/example.vue"); protected testEvent (content: string) {console.log (content);}} @ import ". / common/styles.scss"; body {padding: 0; margin: 0;} section {margin: 20px 0; color: # fff; height: 500px; background: $color-blue } at this point, I believe you have a deeper understanding of the "Vue project first screen performance optimization component method tutorial". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 287

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report