This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!

preface

This article mainly tells the story of a certain process: a small white growth to dafang needs senior front-end development engineers.

Technical text, dry goods, rest assured to watch it.

0. Last Hurrah

“Here, drink! Don’t anybody be a wimp!”

Say that finish, feeling deep, one mouthful frowsty.

Feed, this per capita low consumption Β₯1600, you so drink down afraid not to drink me down.

All of us above the leader floor were called into the dark room for a meeting with only one theme: redundancy. I paid for the party, which looked very lively. You say, a public company wants me to give a list of layoffs, what should I do.

“Here, boss, have a drink. I learned a lot in eldest brother this, technology is true cow ha!”

Clink your glasses and do one.

“I always thought Redis was for the people who wrote Java, but the boss took us to Redis. Now I don’t have to look at those servers anymore! Boss, let’s go!”

Keep clink your glasses. Let’s go. I think I drank the most money so far.

“Boss, I’m in charge of tuning. I used to do HTTP caching and lazy loading. I didn’t expect to learn the tuning method of several higher dimensions from the boss. Here, boss to accompany me to do one.”

Whoa, whoa, whoa, whoa, whoa, whoa, whoa, whoa, whoa, whoa. You’re not supposed to be doing one with the boss. All right, keep clink. One more.

“Hello, everyone listen to me, I tell you a boss of the embarrassment how?”

There were a few girls in the group, and sure enough, girls in all walks of life liked to share gossip. If some people sing, others will support them. After a wave of heckling, a small story came out.

“When I first came to the company, the boss was always calling back all the code I submitted. Once, I submitted code six times and got called back every time. Then I started to cry, half angry, half afraid. I remember I asked you specifically at that time, is the boss particularly strict, will you submit the code back. Then you tell me that none of you got hit back by the boss.”

I began to cover my face, this kind of thing can come up with, also not colorful?

“And then, that’s not the point. The point is, the boss invited me to dinner the other night. Call back my code during the day how hard, evening please have a meal on how humble. The eldest brother while eating to apologize to me, said that my code is not up to standard, page render more times. For example:”

function Com (){
    const [price,setPrice] = useState(0); // Initialize 0 for the first time
    
    useEffect(() = >{
        // fetch data
        setPrice(10.8); // Get the real price the second time
    },[price])
    return <div>Selections {price}</div>
}

// Change the style

Api.fetch().then(
    (props) = >{
        render(React.memo(Com),props)
    }
)

function Com (props){
    const [price,setPrice] = useState(props.price); // Initialize 0 for the first time
    useEffect(() = >{
       // code 
    },[price])
    return <div>Selections {price}</div>
}

Copy the code

“You all see, although I feel reasonable, but because this hit back 6 times, eldest brother, beg you to do individual well πŸ˜‚. Then he apologized and asked me to change the code.”

Oh, yeah! The first one couldn’t hold back his drink and squirted it out. I know, everyone left me in situ embarrassed πŸ˜…. I still keep a smile, smiling in the face of the bleak world.

‘Oh, wait, wait, all of you! What is this? Sometimes the visuals will give you little pictures of that ground-glass effect, right? However, one time the boss decided that we were using too many graphics resources and forced us to use CSS to create ground-glass effects. You say, the boss is not a hard man!”

<div class="mark">The eldest likes the ground-glass effect of manual adjustment</div>
Copy the code
$img: 'https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/388f7a44af6b4ea3af893a1fcbfadd71~tplv-k3u1fbpfcp-watermark.image';

body {
    height: 100vh;
    display: flex;
    background-image: url($img);
}

.mark {
    position: relative;
    margin: auto;
    width: 500px;
    height: 400px;
    background-color: rgba(255.255.255.0.5);
    overflow: hidden;
    z-index: 10;
    line-height: 300px;
    text-align: center;
    color: #FFFFFF;
    font-size: 20px;
    
    &::before {
        content: "";
        position: absolute;
        background-position: top;
        filter: blur(8px);
        background-image: url($img);
        background-repeat: no-repeat;
        background-attachment: fixed;
        background-size: cover;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: -1; }}Copy the code

Oh, hello, hello! I didn’t think I was pushing you! Didn’t we discuss this together?

“Oh, you this with my matter than all normal, not what good logging?”

Not good at words of the small white, our group of a few girls, but also the most beautiful one. Shanghai native, surnamed Bai, is very good at clothes. So, since the first day she joined us, she has had a lot of hassles. Some came to visit her on the basis of work oil, and some even stopped by to chat with her. Even though she wasn’t very good at dealing with them, there were people every day…

Alas, appearance level namely justice! Didn’t you think white was gonna make fun of me?

“You don’t know, the company didn’t send an email to organize a dance team, asking the boss to sign up. I did not dare to ask the boss directly, the boss did not arrange me, and then I wear different good-looking clothes every day, I hope the boss saw can sign me up. But the result, do you know how angry!”

Suddenly, it was very quiet for a while. Big Chapter is in a hurry.

“Small white, you quickly go on to say! People wonder how angry you are!”

“Results! I remember when I was changing my third suit of clothes, which is the third day, my boss suddenly told me that I should leave work early in the evening and not work overtime. The original eldest brother is to think I take off single place object!”

“Poof!”

Several of the mouth still drink can’t hold back, all spray. And laughed all over the floor…

Yeah, these people are so cute. I can bring out such a wave of people, I am satisfied.

1. Do a good job, make a lot of people

After all, big chapter chose to leave. This is what I have discussed with Da Zhang. I recommend a good opportunity to him, and he can get the N+1 compensation here. To my surprise, white came to see me.

Bai said her schoolmate and friend in the next team had been informed that she was on the list to be cut. White wanted to leave on her own, and she asked me to go get her. It’s like a life for a life.

Small white also said, because her name with a “white” word, so call her small white. Little white begged me for two days, this matter has to be said separately. I will not take the initiative to let xiao Bai leave, because xiao Bai’s technology is not enough, and can not go out as big chapter. If it is the small white because of their own things put forward to leave, I may not be able to stop, but this life for a life of practice, I really can not agree.

I think the front end capability level

  1. primaryCan normally execute requirements, code writing experience.
  2. The intermediateCan understand the principles of common technology stacks and write good performance code at the code level and hold a project.
  3. seniorCan stand alone. Be able to timely solve online response problems and provide technical solutions.
  4. seniorAbility to independently undertake commercial solutions.
  5. expertsTechnical breadth should have, but also have depth. Management can hold the business, can do a good job in team building, can improve the overall strength of the team level.

The big chapter is on the edge of senior, while the small white is still in the middle stage. As for Xiao Xiao Bai, it is only in the preliminary stage.

Finally, xiao Bai and Xiao Bai invited me to eat a bowl of hot and sour powder, got me. Xiao Xiao Bai, 22 years old, worked for 2 years. Graduating from a top school at 20 is really a top student. A bowl of hot and sour powder time to tell me the optimization algorithm.

Neural network Based on Chaotic Time Series analysis?

Oh, you don’t understand, do you? To put it another way, one of the main uses of this optimization algorithm is for prediction. For example, it can be used to predict user behavior in the next month and analyze user portraits. Do all the shopping apps on your phone have the ability to recommend products according to your preferences? Why does a shopping APP know which items you like? One of the tools is forecasting.

Oh, my god! Talent! I suddenly feel small. I tried to recommend Whitey to the algorithm team, but I was turned down. Not by the algorithm team, but by Whitey. Small small white said to want to cultivate in me this half a year, cultivate good go to big factory, let once those look down on her feel her vegetables of the people looked up to see her.

All right. It’s good to be young. Let’s start practicing. I’d love to see a little white hit me in the face six months from now, hit those guys in the face. That’s where the Flag is.

Do a good job, the achievement of a group of people. That’s what I do all the time.

2. The first step of practice is to understand the React principle to write React code.

I did the first technical analysis after the people arrived. That’s all. Just get the React Hooks right.

  • Function components execute functions
    • Execution function componentrenderWithHooks
    • changeReactCurrentDispatcherobject
  • Initialize the hooks
    • throughmountWorkInProgressHookGenerate a linked list of hooks
    • throughmountStateTo initialize theuseState
    • throughdispatchActionTo control updates to stateless components
    • throughmountEffectInitialize theuseEffect
    • throughmountMemoInitialize theuseMemo
    • throughmountRefInitialize theuseRef
  • Update the hooks
    • throughupdateWorkInProgressHookFind the correspondinghooksupdatehooksThe list
    • throughupdateStateUp to datestate
    • throughupdateEffectupdateupdateQueue
    • throughupdateMemojudgedeps, gets the or update cache value
    • throughupdateTo obtainrefobject

Here’s an example:

import {useState,useEffect,memo} from 'react';

const Com = React.memo(({name}) = ><div>{name}</div>)

function App(){
    const [ num , setNumber ] = useState(0);
    const [ name , setName ] = useState('white');
    const handerClick=() = >{
        for(let i=0; i<5; i++ ){setTimeout(() = > {
                setNumber(num+1)
                console.log(num)
           }, 1000)
        }
    }
    
    useEffect(() = >{
        setName(num % 2 ? 'white' : 'Little white')
    },[num])
    return <div>
        <Com name={name}/>
        <button onClick={ handerClick } >{ num }</button>
    </div>
}

Copy the code

Q1: What happens when you use hooks (e.g., useState)? 台湾国

Let’s look at the source of useState: react/ SRC/reacthooks.js

export function useState(initialState){
  const dispatcher = resolveDispatcher(); / / 1
  return dispatcher.useState(initialState);
}

Copy the code

Oh, useState(initialState) is equivalent to dispatcher.usestate (initialState). “Dispatcher” means dispatcher in Chinese. So when you call useState, you’re just telling the dispatcher to dispatch the real useState.

Q2:The dispatcher dispatcherWhat is it?

Look at the source code.

function resolveDispatcher() {
  const dispatcher = ReactCurrentDispatcher.current
  return dispatcher
}
Copy the code

Oh, dispatcher comes from ReactCurrentDispatcher. Let’s analyze this, the React current Dispatcher.

In other words, by the time you get here, the Dispatcher has already arranged.

Q3: When is a function component called?

That is, when is your App component invoked? The React 16 architecture can be divided into three layers:

  • Scheduler(Scheduling layer) : Priority of scheduling tasks. High-priority tasks enter the coordinator first
  • Reconciler(Coordination layer) : Build the Fiber data structure, compare the Fiber object to find the differences, and record the DOM operations to be performed by the Fiber object
  • RendererRender layer: is responsible for rendering the changed parts to the page

We know that a render component first builds a linked list of fibers for components. So we come to the source of the coordination layer: the react – the reconciler/SRC/ReactFiberBeginWork. Js


renderWithHooks(
    null.// current Fiber
    workInProgress,      // workInProgress Fiber
    Component,           // The function component itself
    props,               // props
    context,             / / context
    renderExpirationTime,/ / render ExpirationTime); ... renderWithHooks( current,// current Fiber
    workInProgress,      // workInProgress Fiber
    Component,           // The function component itself
    props,               // props
    context,             / / context
    renderExpirationTime,/ / render ExpirationTime
);
Copy the code

Let’s start with renderWithHooks, which are a few of the most familiar parameters. Component is the function itself, props is the information we pass to the function Component, and context is the current context.

So, is it possible that our Component is called in the renderWithHooks method? Moving on to the source code (simplified).


function renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderExpirationTime,) {
  renderExpirationTime = nextRenderExpirationTime;
  currentlyRenderingFiber = workInProgress;

  workInProgress.memoizedState = null;
  workInProgress.updateQueue = null;
  workInProgress.expirationTime = NoWork;

  // 3 is very important!
  ReactCurrentDispatcher.current =
      current === null || current.memoizedState === null
        ? HooksDispatcherOnMount
        : HooksDispatcherOnUpdate;

  let children = Component(props, secondArg); / / 2

  // code ...

  ReactCurrentDispatcher.current = ContextOnlyDispatcher;

  renderExpirationTime = NoWork;
  currentlyRenderingFiber = null;

  currentHook = null
  workInProgressHook = null;

  didScheduleRenderPhaseUpdate = false;

  return children; // end
}

Copy the code

RenderWithHooks returns children, and children = Component(props, secondArg);

Case solved, our function component is called with renderWithHooks and eventually returns.

We go back to 3, ReactCurrentDispatcher. Current didn’t explain the dispatcher in front of the home? ! Explain this line of code: When current is null or current’s memoizedState property is NULL we assign HooksDispatcherOnMount to our dispatcher, Otherwise, assign HooksDispatcherOnUpdate to our dispatcher.

From these two names, we can see a general idea, one is the Mount dispatcher, the other is the Update dispatcher. So, when you initialize an hooks, it’s the Mount dispatcher. When you Update it, it’s the Update dispatcher. !

Okay, this is 80% solved.

Q4: what is workInProgress, workInProgress memoizedState?

WorkInProgress: workInProgress? Is it an object? There must be some property on the object that describes different information, right?

WorkInProgress. MemoizedState:

  • useuseState, savestateinformation
  • useuseEffect, saveeffectobject
  • useuseMemo, saveThe value of the cacheanddeps
  • useuseRef, saverefObject.

That is to say, workInProgress. MemoizedState deposit is the hooks we use information.

Mention here workInProgress. UpdateQueue behind.

Q5: calluseStateWhat happened when.

First look at the simplified source code.

function mountState(
  initialState
){
  const hook = mountWorkInProgressHook();
  
  // If initialState is a function, the initialState function is executed.
  if (typeof initialState === 'function') {
    initialState = initialState();
  }
  hook.memoizedState = hook.baseState = initialState;
  const queue = (hook.queue = {
    pending: null.// The content to be updated
    dispatch: null.// The scheduling function
    lastRenderedReducer: basicStateReducer,
    lastRenderedState: initialState, // The state of the last render
  });

// The function responsible for updating
  const dispatch = (queue.dispatch = (dispatchAction.bind( 
    null,
    currentlyRenderingFiber,
    queue,
  )))
  return [hook.memoizedState, dispatch];
}

Copy the code

Oh, this code is obviously a little easier to analyze.

  1. Get the hook information firstconst hook = mountWorkInProgressHook();
  2. The arguments forinitialStateLet’s check. theninitialStateAssigned tohook.memoizedState ε’Œ hook.baseState
  3. A queue is then declaredqueue, information to see the comments.
  4. Declare the dispatch function, which updates state
  5. Returns an array that we can deconstruct. That is:
const [x,setX] = useState(initialState);
Copy the code

What’s dispatchAction?

function dispatchAction<S.A> (fiber: Fiber, queue: UpdateQueue
       
        , action: A,
       ,>)
Copy the code

What does S stand for against the above code? What does A stand for?

SetX just calls dispatchAction, right? The source code shows that “dispatchAction” already has two parameters: “currentlyRenderingFiber” and “queue”.

Q6: dispatchActionWhat did he do?

function dispatchAction(fiber, queue, action) {
   // code ...
    
  // Step 1: Initialize the information to be updated
  const update= {
    expirationTime,
    suspenseConfig,
    action,
    eagerReducer: null.eagerState: null.next: null,}// Determine if it is the first update
  const pending = queue.pending;
  if (pending === null) {  // Prove the first update
    update.next = update;
  } else { // Not the first update
    update.next = pending.next;
    pending.next = update;
  }
  
  queue.pending = update;
  const alternate = fiber.alternate;
  
  // Determine whether the rendering phase is currently underway
  if( fiber === currentlyRenderingFiber || (alternate ! = =null && alternate === currentlyRenderingFiber)) {
   // code ...
  } else { 

   // code ...
   
   // The dispatching layer will do the rest.scheduleUpdateOnFiber(fiber, expirationTime); }}Copy the code

Q7: What is Fiber? What’s a Fiber list?

Well, take a look at some of the properties on the Fiber object.

type Fiber = {
  / * * * * * * * * * * * * * * * * * * * * * * * * DOM examples related to * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
  
  // Tag different component types. See WorkTag for values
  tag: WorkTag,
  // Div, span, component constructor
  type: any,
  // Instance objects, such as class component instances, native DOM instances, and function component does not have instances, so this property is empty
  stateNode: any,
 
    / * * * * * * * * * * * * * * * * * * * * * * * * build Fiber tree related * * * * * * * * * * * * * * * * * * * * * * * * * * * /
  
  // Point to its parent Fiber object
  return: Fiber | null.// Point to its first child, the Fiber object
  child: Fiber | null.// Point to the next sibling iber object
  sibling: Fiber | null.// In the process of updating the Fiber tree, each Fiber will have a corresponding Fiber
  Current <==> workInProgress
  // They switch positions after rendering
  // alternate refers to the corresponding Fiber in the workInProgress tree
    alternate: Fiber | null./ * * * * * * * * * * * * * * * * * * * * * * * * state data related to * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
  
  // Props to be updated
  pendingProps: any, 
  / / the old props
  memoizedProps: any,
  / / the old state
  memoizedState: any,
        
  / * * * * * * * * * * * * * * * * * * * * * * * * side effects related to * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
  // Updates generated by components corresponding to this Fiber are stored in this queue
  updateQueue: UpdateQueue<any> | null.// Record the DOM operations performed by the current Fiber
  effectTag: SideEffectTag,
  // Stores the DOM operations to perform
  firstEffect: Fiber | null.// The single linked list is used to quickly find the next side effect
  nextEffect: Fiber | null.// Store sub-leases after DOM operations, such as calls to lifecycle functions or hook functions
  lastEffect: Fiber | null.// Expiration time of the task
  expirationTime: ExpirationTime,
  
    // See TypeOfMode for details about the rendering mode of the current component and subcomponents
  mode: TypeOfMode,
};
Copy the code

In React 16, the whole task is divided into small tasks for processing, and each small task refers to the construction of a Fiber node.

As for the Fiber list.

React uses a linked list structure to find the next task unit to execute. To build a linked list structure, you need to know each node’s:

  • The parent nodeWho is it
  • The child nodeWho is it? You need to know his
  • The next sibling nodeWho is it.

The list of attributes attached to the Fiber object is detailed. I need you to take a look.

When all of the DOM’s Fiber objects are generated, the Fiber that needs to perform DOM operations will build the list of fibers. As for the principle of building the Fiber list, the following code (not source code, but just to see more clearly, manually written wave. Hope you have time to write again manually) :


import React from "react"
const jsx = (
<div id="a">
 <div id="b1">
   <div id="c1">
        <div id="d1"></div>
        <div id="d2">
            <div id="e1"></div>
            <div id="e2"></div>
        </div>
   </div>
   <div id="c2"></div>
 </div>
 <div id="b2"></div>
</div>
)
const container = document.getElementById("root")
/** * 1. Create a Fiber object for each node * 2. 3. Submit Fiber link */
// Create the root element Fiber object
const workInProgressRoot = {
stateNode: container,
  props: {
   children: [jsx]
  }
}
let nextUnitOfWork = workInProgressRoot
function workLoop(deadline) {
  // If the next execution unit to build exists and the browser has free time
  while (nextUnitOfWork && deadline.timeRemaining() > 0) {
   // Build the execution unit and return the new execution unit
   nextUnitOfWork = performUnitOfWork(nextUnitOfWork)
  }
  // If all execution units have been built
  if(! nextUnitOfWork) {// Go to the second stage to perform DOM operations
   commitRoot()
  }
}
// The first phase of the Fiber operation
function performUnitOfWork(workInProgress) {
  // The process of going down in the construction phase
  // 1. Create a DOM object for the current Fiber node and store it in the stateNode property
  // 2. Build the sub-fiber object
  beginWork(workInProgress)
  // If the child exists
  if (workInProgress.child) {
   // Return child builds child's child
   return workInProgress.child
  }
  // Start the upward movement in the construction phase
  // If the parent exists
  while (workInProgress) {
   // Build the Fiber list
   completeUnitOfWork(workInProgress)
   // If the sibling exists
   if (workInProgress.sibling) {
     // Return children of the sibling build sibling
     return workInProgress.sibling
   }
   // The parent level does not exist
   workInProgress = workInProgress.return
  }
}
function beginWork(workInProgress) {
// If the Fiber object does not store its corresponding DOM object
if(! workInProgress.stateNode) {// Create a DOM object and store it in the Fiber object
 workInProgress.stateNode = document.createElement(workInProgress.type)
 // Add properties to the DOM object
 for (let attr in workInProgress.props) {
   if(attr ! = ="children") {
     workInProgress.stateNode[attr] = workInProgress.props[attr]
   }
 }
}
// Create a child Fiber object
if (Array.isArray(workInProgress.props.children)) {
 // Record the last time the child Fiber object was created
 let previousFiber = null
 // Iterate over the children
 workInProgress.props.children.forEach((child, index) = > {
   // Create a child Fiber object
   let childFiber = {
     type: child.type,
     props: child.props,
     return: workInProgress,
     effectTag: "PLACEMENT"
   }
   // The first child is mounted to the parent's child attribute
   if (index === 0) {
     workInProgress.child = childFiber
   } else {
     // Other children are mounted in the sibling property of their previous sibling
     previousFiber.sibling = childFiber
   }
   // Update the previous child
   previousFiber = childFiber
 })
}
}
function completeUnitOfWork(workInProgress) {
  let returnFiber = workInProgress.return
  if (returnFiber) {
   // Move the chain head
   if(! returnFiber.firstEffect) { returnFiber.firstEffect = workInProgress.firstEffect }/ / lastEffect up
   if(! returnFiber.lastEffect) { returnFiber.lastEffect = workInProgress.lastEffect }// Build the list
   if (workInProgress.effectTag) {
     if (returnFiber.lastEffect) {
       returnFiber.lastEffect.nextEffect = workInProgress
     } else {
       returnFiber.firstEffect = workInProgress
     }
     returnFiber.lastEffect = workInProgress
   }
  }
}
// The second phase of the Fiber operation
function commitRoot() {
// Get the first DOM operation to perform in the list
let currentFiber = workInProgressRoot.firstEffect
// Check whether the Fiber object to perform DOM operations exists
while (currentFiber) {
 // Perform DOM operations
 currentFiber.return.stateNode.appendChild(currentFiber.stateNode)
 // Retrieve the next Fiber object from the list to perform DOM operations
 currentFiber = currentFiber.nextEffect
}
}
// Start the build while the browser is idle
requestIdleCallback(workLoop)
Copy the code

2. After 1 hour online, Xiao Xiao Bai cried

It’s been two weeks since I last shared something about React Hooks. Xiao Xiao Bai study hard, the company overtime write requirements, go home to continue to work overtime to write code.

Am I pushing people too hard?

The dog barks (my cell phone rings).

“You how to return a responsibility, the operation says the line is out of order! This is how you repay me for promising to keep one of you…”

Pa! I’ll hang up. He didn’t say anything. He just hung up. I quickly returned to the position, little white tears on the verge of crying dizzy on the station. I at this time should spray 1: MMP, have an accident to know to cry, have a problem you pour the first time tell me!

The thing is that Xiao Xiao Bai made an activity page, the content is to let the user click on the screen to grab a red envelope. The problem is that a user can tap on a red envelope and grab it — in theory, as long as the hand is fast enough for the screen to recognize the user’s gesture. So if you tap 1,000 times, you’ll get 1,000 red packets. Of course, that’s an exaggeration. Users can grab up to 200 yuan, and no more than that.

User hand speed can not be fast enough to that extent, but small white activity page, grab 3, 4 red envelopes when the animation appears very slow. Users clearly selected but did not grab the red envelope, the problem was reported by the activity operation.

Now that I know what’s going on, MY phone has been dialed to an operations boss.

“What about this problem, Old tie?”

“There have been dozens of complaints so far, but expect a lot of traffic. I’ve asked my staff to stop promoting this page for now. What’s going on over there?”

“Here, iron. You do not let the suspension of promotion means, your side of the process as usual, half an hour do not take the real activity address, you can first the whole preheat activity.”

There was silence for a dozen seconds. I know she will help me.

“Are you sure everything will be all right in half an hour?”

“Can.”

“When it’s done, date me.”

Pa! Cell phone in the drawer, fucking date, god comes don’t bother me!

I walked to xiao Xiao bai, she is still lying on the crying. Small white in comfort, see me come over.

“How, boss?

“Get out of the way.”

I sat in white’s seat.

“Screen lock password.”

“110gaosuwoyaodidiao” (110 tells me to keep a low profile)

I remember that xiao Bai is going to have an SDK for automatic burial today, but it is expected to be at night, and he is still doing the final return during the day.

“Small white, can I believe you?”

“Yes.”

I open VSCode and ambush a hacker code on the SDK. We have done several things:

  • All margin and padding properties are translated to translate
  • All calculations related to the red envelope price are deferred. First record the user click data, unified in when the end of the activity time unified calculation.
  • Injection requestIdleCallback

It’s dangerous. No testing, no validation. It’s not even legal. But it doesn’t get any worse than this.

Commit code. Skip the pre-launch environment on test directly (simulate the online environment before going online).

“Small white, take your mobile phone out.”

I looked at the clock. It had been 15 minutes. At this time little white stopped crying, should be scared by me.

“Xiao Xiao bai, in five minutes to test the machine over there to run. Can it be done?”

Small small white mechanical type of the point nodded, then ran to take a mobile phone.

I was staring at my phone for 21 minutes, and I went online. Little white suddenly pulled me.

“Boss, here is a millet 6, still a little slow.”

I took a look, and when I clicked on the red envelope, THERE was a slight wobble. Then no reason little white, online. I used my permission to force a self-test iteration online.

After the operation, it is waiting in line. I suddenly asked a little white.

“Little white, can I trust you this time?”

I saw the panic in her eyes, but she bit her lower lip and nodded to me. I went back to my desk and pulled out my phone. The number of missed calls choked my screen.

I walked to my boss’s office and knocked on the door. The boss threw the glass of water against the door.

“Now you are awesome! Take your eyes off me! The boss of the operation to the business side of the matter, the problem has risen to the European general (CEO) that. Do you he hide what hide, the first time solve the problem to know?”

Alas. The operation department is really a chicken feather, that I operate old iron is a northern girl, the estimate is an operation old four old five, as for that boss, I made a contradiction with him. I think he’s the one who put it up there.

I pretended to be calm and closed the door to isolate the outside sound. My gut tells me my kids are looking at me.

“Boss, what’s going on?”

“Your people broke down, what are you asking me? !”

I checked the time. Almost there. I in front of the boss, take out the mobile phone, dial the phone to old iron, open the tone.

“Well, what’s the matter? I’m busy with events right now.”

“Isn’t there something wrong?”

“Out of order? Are you? My side of the activity is normal, did not hear who said the problem ah.”

“Good. Then you busy first.”

I hung up the phone, the eyes doubt of looking at the boss: “boss, TODAY I seem to be a new activity page online, cheat users to grab a red envelope.”

Say that finish. I took out my phone, pretended to find the activity page, and played for a while. Play the game and then show the results to your boss.

“Boss, isn’t this good?”

And then I pretended to call White.

“Hey, did you do today’s activity page? I’ll be in the director’s office.”

Unexpectedly, small white came in, I see her face actually can not see a trace of crying, to have more calm calm. I had White run through each of the machines.

“Boss, where did you hear that wind is rain? Isn’t it normal to have dozens of complaints at the beginning of an activity page? I was just talking to my mother-in-law about the bride price and I didn’t notice my phone ringing.”

Coming out of the boss’s office, I clearly heard the little white gulp of breath behind me.

“Afraid of? Go, today there are online demand for people to eat a midnight snack.”

In the middle of the night, it’s all verified online. I’ll tell you when we masturbate.

“Calm down if something goes wrong. The big deal is being fired. It’s not a day or two since that director didn’t like me, but I dare to tell him off! Not only should you be able to write code, but more importantly, you should be able to solve problems…”

In fact, there are some things we all understand, xiao Xiao bai drank a beer, drinking poor, crying again.

3. Xiao Xiao Bai is interested in performance optimization

After the “breakdown” incident, xiao Xiao Bai is not pestering Xiao Bai is pestering me, the purpose is to know how to solve the problem of grabbing red envelope card.

So let’s analyze that. Stalling can be detected by user feedback or performance monitoring. For example, we received complaints from users that the active page card could not grab the red envelope. Then, after checking the performance indicators on the performance platform, we found that the page had 10 consecutive frames over 40ms, which is a serious lag.

How to deal with it?

Check to see if there is a data problem with the server. This can be done by capturing packets or viewing server exception logs.

If the problem is at the front end, it’s usually one of two things: the browser’s main thread and composite thread are not properly scheduled, and computatively time-consuming operations.

Take this activity page (red envelope rain) for example, the user complained that the card, it is intuitive feeling, high probability and animation effect. There are many different kinds of animations, but the main thing is CSS computing.

The main thread of the browser is responsible for running JavaScript, calculating CSS styles, and laying out elements, while the compositing thread is responsible for drawing the UI. When width, height, margin, padding, and so on are animated as transition values, the main thread is stressed because calculating CSS styles is also time consuming. How to use transform instead of setting margin and padding directly?

Take chestnuts. Add the DOM element margin-left: 0px to represent the red envelope, and the final red envelope is margin-left: If step = 1, then the main thread of the browser will be calculated 100 times from 0 to 100. After each calculation, the main thread will be drawn to the GPU and rendered to the screen. This process, the browser can imagine how much pressure.

However, if you use Tranform :translate(-100px,0) and the main thread of the browser calculates it once, the compositor-thread can draw 100 directly from 0. One can imagine the gap.

On the other hand, calculate time-consuming operations.

  • The Virtual DOM is designed to solve the performance problem caused by frequent DOM operation. If you want to operate 100 DOM, store the operation information on the Virtual DOM first, and update the Virtual DOM to the real DOM once all the operations are completed. Do React and Vue take an informal Virtual DOM route?

  • Js is calculated. For example, grabbing a red envelope has a large or small amount, JS is a single thread, has been responding to the user’s operation, you want JS to calculate at this time, that can only let JS single line to calculate the amount, the user’s behavior temporarily put aside, you said that the user does not feel the card is a ghost. There are two ways to solve this problem.

    • Delay js computation and wait until all tasks with high priority are finished.
    • If you must calculate results in a timely manner, try to do so in the free time of the browser.

Here’s a point to make.

The page is drawn frame by frame, and when the number of frames per second reaches 60, the page is smooth. Below that, the user feels stuck.

There are 60 frames in 1s, and the time allotted to each frame is 1000/60 β‰ˆ 16ms. If the time allotted to each frame is less than 16ms, the browser has free time.

If the task is not completed within the remaining time, it will be stopped and the main task will continue to execute first, which means that requestIdleCallback always takes advantage of the free time of the browser to execute the task.

One weekend, 11 a.m. I was still sleeping (too tired), little white called.

“Hey, boss, you’re still sleeping! Small white said to play badminton, everyone called up, on the difference you.”

Pa! I threw the phone away. Not long after, the phone began a deadly serial call pattern. Okay, I lost, I was wrong, I got it back…

“Well, give me one good reason why I shouldn’t. Otherwise block!”

“& % @! Selections % * (,”

“In human language!

“I say you are a deceitful womanizer, where were you last night? Do you think you’ve already forgotten the date you promised me? !”

All right. Operation Old iron Hello, I was wrong. You know I’m a deceitful womanizer, so is it my fault you forgot?

“Old iron, I call you old iron, you will find old iron date?”

“How hard is it to get dinner without a date?”

The phone suddenly very serious to come so a sentence. There seems to be something wrong with me.

“I’m about to leave, can’t you treat me to dinner? Can you spare some time for dinner?”

I quickly hung up the phone, the wechat group has exploded. Organization structure adjustment, operation boss promoted VP, operation old iron to leave. My sleep vanished, and another very crazy idea occurred to me.

This stupid girl can’t be afraid of getting into trouble with the boss of operations to settle last time. What happened last time is settled. It was a misunderstanding. But the VP has a lot of authority. If the case is reversed…

So, everything you do as an adult comes at a price, and the workplace is no exception. I’m glad I have some close colleagues who are more like friends.

New Monday, old iron gone. Oh, this if did not have the leadership to agree, which can so quickly go. I look at the kids under my watch, and they’re all doing their own thing. I looked at the leader’s office, and suddenly I had a decision. It’s time for me to leave.

Just wait six months like white promised. So I went on a technology sharing spree.

4. Summary of front-end performance optimization

In fact, the most important indicator of front-end performance is”fast“, really can not quickly choose”To cheat or cheat.“.

Fast:

  • Request resources

    Static resources such as Html, JS, CSS, and images are essentially obtained from the server. However, it takes time for the server to respond to a client request. The larger the volume of returned resources, the longer the time is. So there are three things to think about in terms of speed.

    1. Reduce the resource size.
      • To optimize thewebpackPackaging,treeShaking 、CodeSplit etc., try to ensure that the volume after packing is not too large.
      • Larger, more pictures and other resourcesCDN, which also reduces the package volume in a disguised way. Direct reference in codeCDNThe link.
    2. The priority of the load resource
      • For example, the first screen, only need to render the contents of the viewable area first, non-critical load can be delayed.
      • Key data can benativeMake the pre-request and hand the critical data directly to H5
    3. The cache
      • HTTP cache
      • Local cache.For example, Native caches image resources
      • Interface cache.
  • Loading way

    1. Lazy loading
      • Skeleton screenFind out.
    2. preload
      • NSRFind out.
    3. Cache loading
      • CSRLook at the
    4. The offline package
  • The webview optimization

    1. Parallel initialization
      • The so-called parallel initialization is when the user is enteringApp, the system is createdWebViewAnd load the template, soThe WebView initializationAnd App launch can be carried out in parallel, which greatly reduces user waiting time.
    2. Resource preloading. Resource preloading refers to placing a static list of resources in the initialized WebView in advance, and later loading the page will be faster because the resources are strongly cached. Static resources to be preloaded can be placed in:
      • A constant outer chain for a certain period of time;
      • Some basic frameworks, multi-adapter JS (such as Adapter.js), performance statistics SDKS or third-party libraries (such as React/viee.js);
      • For the basic CSS layout, such as base.css.
    3. The other. How native provides apis for interface requests can also be optimized for interface requests.

    Ps: Don’t underestimate the WebView, it can save you 100-200ms.

The subtotal

  1. Optimization scheme during APP startup

    • The webview optimization
  2. Page white screen stage optimization scheme

    • Offline design, such as offline packages
    • Skeleton screen
    • SSR
    • NSR
  3. Optimization of the first screen rendering stage

    • Optimize the number of requests
    • Interface preloading
  4. DOM Performance optimization

    • Long list optimization.Memo, usememo
    • To reduceRenderThe number of
    • Js computational optimization
  5. The performance platform

    See another story for more information

5. The end of time

When I realized the time had come, I received a cold call from a company inquiring about the situation of xiao Xiao Bai.

Yeah, the last six months are almost over. Little white is growing up like a rocket. I took a good look at this lovely group of friends, AND I saw that everyone was starting to work independently, even if I left them.

I secretly used another wechat to add Xiao Xiao Bai’s friend, in the name of helping her to tweet and xiao Bai’s hot. Alas, as expected young is good cheat, the trick that this kind of slightly leave a heart eye to be able to be exposed to expose to cheat small small white comfortable.

I first asked for Xiao Xiao bai’s resume, gave some advice, and helped to modify.

In fact, the cleanest resume is to ensure that HR and interviewers can quickly match your resume. That way, there will be no misunderstanding and no time wasted on either side. For example, some people like to include all the technology they know, such as node.js, in their resume, and the interviewer will ask about node. You can imagine the result.

I like to have a piece of personal information on my resume.

Personal resume! == Work experience.

A resume is more like a description of what you’ve done in the past. Here’s an example:

2. Have rich experience in the front-end development and management of toB and toC business, controlling project progress and promoting partners to achieve goals. 3. I like to study new technologies, am extremely keen on improving project performance, and devote myself to updating them into online products.Copy the code

Work experience

One of the essential contents. In addition to clarifying your working hours, you also want to clarify your current role. And of course the business content that you were responsible for in the company.

Project experience

Please write according to the template below

  1. The project name
  2. Your role in the project
  3. Be brief and to the point
  4. What did you give
  5. What are the effects/results: such as what you did, increased conversion rate, how much money you made, how many KPIs you achieved. I want the numbers to stand out.

Self assessment

I want your self-assessment to be straightforward about what makes you great.

For example;

  1. Have practical experience in XXX
  2. Studied the Vue source code
  3. Good at project infrastructure

I don’t want to see words like mastery, familiarity, and understanding. Because there are a thousand Hamlets in the eyes of a thousand people, perhaps your mastery is the interviewer’s familiarity? Instead, explain how much technical research you’ve done.

Put it at the end

Swastika ha! Xiao Xiao bai’s story actually did not finish, plot some dog blood. Is that xiao Xiao bai finally went to the big factory, and then found the truth.

But it is not important, the result is good, after the end of each good is.

Bye, white.

Goodbye, men who cheat on women’s feelings.

Small small white finally call spray me of, who let me so “lick dog type” practice. Even if the truth has been exposed, it is still not admitted πŸ˜‚πŸ˜‚πŸ˜‚.

I wish you well. I hope you have grown from this long story! In addition, details not covered in this article may be covered in the next article.)