JavaScript triggers onscroll event's function throttling detailed _javascript skill

Source: Internet
Author: User

Problem description

Common site layout, the top of a navigation bar, we assume that this page has a total of four columns: respectively A, B, C, D, we click a, anchor jump to a column, while the top of the a button highlighted; Click b, anchor to jump to column B, while the top of the B button highlighted; We scroll in the main assembly, When you scroll to the B module, the B button is highlighted. These are a few of the models that we often encounter in development. In the past, using jquery as a front-end development is too familiar.

Solution

I want to talk about the performance optimization method in react component development.

The structure of our page is like this

<div
 Classname={style.main}
 id= "main"
 ref={(Main) => {this.main = main;}}
 onscroll={(
 (/detail/.test (this.props.location.pathname))? (() => this.throttle () ()): null
 }
>
 {this.props.children}
 <footer/>

We set the Onscroll event in the main assembly, in which we trigger the action and pass the change of state to the subassembly by redux.

My scroll event triggering function is like this (ignoring a long string of if else, this is the ultimate solution to an afternoon bug, which is not described in this article)

 Handlescroll () {const {Changescrollflag} = this.props.actions; Modify the Titlebox style based on the scrolling distance const {basicinformation, holderinformation, mainpeople, Changerecord} = {Basicinformation:doc Ument.getelementbyid (' basicinformation '). offsetTop-121, Holderinformation:document.getElementById (' Holderinformation '). offsetTop-121, Mainpeople:document.getElementById (' Mainpeople '). offsetTop-121, Changerecord:
 document.getElementById (' Changerecord '). offsetTop-121,};
 if (Window.screen.availHeight > This.main.scrollTop) {document.getElementById (' gototop '). style.display = ' None ';
 else {document.getElementById (' gototop '). style.display = ' block '; //Get the offsettop of the base information area, the shareholder information area, the main personnel area, the change record area, and we use it to trigger the action against the ScrollTop comparison//comparison result of main, and change the Titlebox component style if ( This.main.scrollTop < Holderinformation) {//Base information area if (basicinformation = = 121) {//If the underlying information module does not exist, we do nothing (theoretically, of course)
 Information modules should be available) return;
 } changescrollflag (1);
 Return else if (This.main.scrollTop < mainpeople) {//Shareholder Information Area Changescrollflag (2); if (holderinformation = = 121) {//If the shareholder information column does not exist, we should not force the Tilebox highlight button to be set to holderinformation when scrolling.
 Since holdinformation does not exist, we jump to the previous button and let the underlying information button highlight Changescrollflag (1);
 Return
 } return;
 else if (This.main.scrollTop < Changerecord) {//main personnel area Changescrollflag (3); if (mainpeople = = 121) {//If the main personnel column does not exist, we should not force the Tilebox highlight button to be set to Mainpeople//mainpeople does not exist when scrolling, we skip to the previous button,
 Let the underlying Information button highlight Changescrollflag (2);
 if (holderinformation = = 121) {//If the main personnel column does not exist, and even the shareholder information column does not, we jump to the highlighted basic information column changescrollflag (1);
 Return
 } return;
 } return;
 else if (This.main.scrollTop > Changerecord) {//with the above empathy//change record area changescrollflag (4);
 if (Changerecord = = -121) {Changescrollflag (3);
 if (mainpeople = = -121) {Changescrollflag (2);
  if (holderinformation = = -121) {changescrollflag (1);
 Return
 } return;
 } return;
 } return; }
}

Where the changeScrollFlag() function is our action handler function.

Our function throttling

Throttle () {
 //onscroll function throttle let
 previous = 0;
 Previous the initial setting of the Onscroll function was last called with a time point of 0. Let
 timeout;
 const WAIT =;
 250 MS Trigger once return
 () => {
 const now = Date.now ();
 const remaining = wait-(now-previous);
 if (remaining <= 0) {
 if (timeout) {
 window.cleartimeout (timeout);
 }
 previous = now;
 timeout = null;
 This.handlescroll ();
 } else if (!timeout) {
 timeout = window.settimeout (this.handlescroll, wait);}}

Our throttle function returns a function, sets a timestamp, if our timestamp is smaller, we do nothing, but our timestamp has a larger margin, clears the timer, and triggers the scroll function. It seems to be quite simple, yes, it's quite simple.

So what do we need to do with subcomponents?

Receive action

The secondary container-type component receives action and passes the props to level three display components through a Level two container-type component.

We must receive this props in Componentwillreceiveprops.

Remember, using in Componentwillreceiveprops this.props is not a props to receive changes in the!!! The component lifecycle function contains one of its own parameters.

 Componentwillreceiveprops (nextprops) {
 //The change in the Onscroll event triggered in the main component in the Compowillreceiveprops activebtn style index
 //And the state
 this.setstate ({
 activebtn:nextProps.scrollFlag.scrollIndex,
 }) set to this component;

Our state controls which button we highlight is number one, and it is a digit.

Change the style of a navigation bar

Here, I use the library around react: Classnames, see its APIs for details.

<span
 classname={classnames ({
 [style.informationactive]: (this.state.activebtn = = 1),
 })}
 onclick={() => This.handleclick (1, ' basicinformation ')}
>

Here we have completed a process of triggering events from top level components and doing function throttling to pass the event layer to the underlying display component.
Some recent regrets about the front-end development

    1. Do not repeatedly call a function in the assembly, which can cause huge consumption! We can do things by using ternary operators, template strings, and do not write a new function.
    2. Jsx not too much redundancy. We try to write the form of variables, otherwise the page structure is complex, not easy to catch bugs.
    3. Reduce the backend request, can save cookies stored cookies, can save Localstorge is localstorge.
    4. Simple components to write as much as possible, do not use other people's components, or in need of change, style adjustment will appear great difficulties and do some meaningless things.

Summarize

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.