preface

These front-end performance optimizations are things I never tell people

The introduction

When it comes to “What are you doing for performance optimization?”

  • 70% cited optimization techniques such as reducing merge resources, reducing requests, and caching data.

  • 15% mentioned the need to look at the first screen time in DevTools and optimize around the first screen;

  • 10% mentioned the need to access a performance platform to see what was going on and diagnose;

  • Only 5% of the students will systematically consider performance optimization in terms of the front-end performance architecture.

Do you have an answer? If you’re the interviewer, or the person in charge, what kind of person would you want?

No doubt I would want the 5%. This article is different from the previous one. But I still hope that you can see the first chapter, at least to the performance system can have a vague concept.

Front-end performance system

Here’s an example. Your boss’s boss crosses the hierarchy and calls you one day and says, “I opened the front page very slowly, but I didn’t open it again. What’s going on here? Do users have the same problem as I do?”

Tell me honestly, how would you answer your boss’s boss (e.g., CEO)? In order not to take a big responsibility, would you tell your boss’s boss that it’s because of the user’s poor Internet connection?

So the bigger question is, is this going to happen over a few days, or at random? Can you always find a reason your boss will accept? No, you can’t.

The home page is slow to open for a number of reasons. The boss expects that the front-end, like the server, will be able to locate problems by checking the logs. Guess what happens to you if you don’t solve the problem at the guessing level? In fact, not many people can do this.

So, is there anything like a server-side tool on the front end? Yes, that is the performance monitoring platform. Or maybe you should build a performance monitoring platform. The platform can monitor the performance indicators of each service and the performance standards in the corresponding scenarios. When it comes to performance issues, you can directly determine what the current performance metrics mean. The platform will then tell you whether the problem is front-end, server, or network layer.

So what is front-end performance architecture? You can initially understand it as a collection of performance indicators, monitoring, warning, and even alarm various combinations of elements in the collection.

So again, where do performance metrics come from?

Analysis of the whole process from URL input to page loading

When you enter the URL in the browser and press Enter, the browser sends a DNS query to the DNS server to obtain the IP address. The browser then finds the destination server using the IP address and initiates a TCP three-way handshake and TLS negotiation to establish a TCP connection.

After a TCP connection is established, the browser initiates an HTTP request, and the server responds to the received request. The browser then takes the data from the response, parses it, renders it, and presents a web page to the user.

So, is there a front-end performance bottleneck in this process? In terms of time, can this process be seen as three stages? I’m going to give you an overview of the performance bottlenecks of the Web front end

The client initiates a request

If a user enters a URL in the browser and matches the URL in the local cache, the URL is directly removed from the cache. If the cache is not matched, the DNS server obtains the IP address from the DNS server. Then, the client sends an HTTP request to the server to establish a TCP connection through TCP three-way handshake and TLS negotiation.

No, local caching, DNS queries, and HTTP requests can all be performance bottlenecks at this stage. Got it?

  • The local cache(This point is not to say, so as not to be part of the official said “old four”/manual face covering)
  • The DNS query
    • Each DNS query must go through the whole process from the mobile phone to the mobile/telecom signal tower, and then to the authentication DNS server. The point is that the process is long enough for users to wait unacceptably long.

    • To save time, you can remove DNS queries from the cache, and browsers provide DNS prefetch interfaces. We can do this at the same time we open a browser or WebView. In this way, when a request is actually sent, DNS resolution can check the browser cache. Once the cache is hit, there is no need to query the DNS server.

  • The HTTP request
    • The biggest bottlenecks in HTTP/1.1 are serial file transfers and the number of connections to the same domain name. I don’t want to repeat it here. I mentioned it in the previous article.

The server handles the request phase

  • Data cache
    • With the help ofService WorkerData interface cache
    • With the help of local storage interface cache andCDN(Content Delivery Network, Content delivery Network)
    • Why is data caching a performance bottleneck? This is because each request for the data interface needs to go from the client to the back-end server, and then to the back-end data storage layer. It takes a long time to return data layer by layer, and finally to the client. If we can reduce the request once, we can gain valuable time for the header screen.
  • redirect
    • Redirection refers to the relocation of site resources (such as forms, the entire site, etc.) to another location. The process by which a user requests to be moved from one page to another while visiting a site.

    • In the server-side processing phase, redirects fall into three categories (all causing new DNS queries and new HTTP requests).

      • Server side play 302 redirection,
      • META tags implement redirection and front-end javascript
      • Redirection via window.location.

Client page rendering stage (get the data and start rendering the page)

  • Bottlenecks in building a DOM tree(Wait for a future Virtual DOM -> Real DOM article)
  • Bottlenecks in the layout
    • Take, for example, the Sprite picture that Tong Mentioned in the last comment. Here’s a quick question: Is Sprite a good idea for your home page?
  • Js calculation
    • For example, red envelope rain
    • Like a long list

So that’s the bottleneck we can change in the front end. There are other aspects that I haven’t mentioned.

  • For example, operating systems. I used to work in a15Inch screen to do the first screen seconds open, remember is the operating system isThe Android 5.3Version. How bitter, when you think about it.
  • GPU,GUIAnd so on.
  • Network layer and service layer
    • Prevent blocking
    • Load balancing
    • Slow start
  • algorithm
    • Page parsing, rendering algorithm
    • Tokenization algorithm
    • Tree building algorithm
    • GC

Build a performance monitoring platform?

There is no fully functional product on the market right now. Even if there are, there are no good open source projects. But it’s not that hard to build a simple performance monitoring platform for just one part of a company.

Prep one, get the data buried.

The purpose is to obtain a portion of the reported data. For example, the number of times the page was visited in an hour, the number of times the page went wrong, which location and entry had the most hits, etc. Let’s talk about some ways to bury them.

  • Manual embedding (code embedding)

    • Pure manual code, call the embedded SDK functions. Call the interface at the service logic function location to report buried data. At present, most third-party data statistics service providers (such as Baidu) in the market adopt this scheme.

    • What is the technical nature of manual embedding? What does it get?

      • Domain name: document. DomainURLdocument. URL
      • Page title: document.title
      • Resolution: window.screen.height & window.screen.width
      • ColorDepth: window.screen.colordepth
      • Referrer: document. The Referrer
      • Client language: Navigator.language
    • Buried point of practice

      // Command burying point() = > {/ /... Here is your business logic code
          sendData(params);  Params is the buried data that you encapsulate
       }
      // Declarative burying point
      <div data-spm-data="{name:' click ',enevt:'touch',agent: '... '}">Touch</div>
      Copy the code
  • Visual burial point

    • Solved the pure manual buried point development cost and update the cost, through the visualization tools rapid configuration acquisition node (marks), on the front end automatic parsing configuration, and upload buried point according to the configuration data, compared with manual buried point look more perfect, the configuration data can set the filter conditions, avoid against all elements (such as the buried point), When the AUTOMATIC monitoring API is invoked, you can set some feature attributes to filter the elements that do not meet the requirements, so that only certain elements can be automatically reported. (I won’t go into this too much detail. Maybe later.)
  • Unburied (wait…)

Preparation two: Define performance metrics and quantify metrics data

  • Indicator quantization scenario
    • Weak network
    • No network is available
    • models
    • Network transient exception
  • indicators
    • Blank screen time
    • FPS
    • Page opening rate per second
    • Page error rate
    • Page lag times

Development.

Now that you have everything figured out, you can really try to develop a simple version of the performance monitoring platform.

Skeleton screen

Why do I have to separate it out. That’s because skeleton screens do one important performance metric: render data to page time.

So, what do you think a skeleton screen is? For example, what about the following?

Yeah, it’s a skeleton screen.

Q: Is that all the skeleton screen can do? A: You are wrong. If skeleton screens are coming fast enough, why don’t I add something else to skeleton screens? Here’s an example.

As shown in the picture, this card content consists of three parts: product picture, product name, buy now button. What if your skeleton screen could get text-related data in advance? You might want to consider putting the names of these goods in the skeleton screen as part of the screen.

In fact, I discovered this problem when making component skeleton screens. Aside from the time it takes to fetch data, the component skeleton screen renders a text node in negligible time. So, the question shifts to the data. What if you cached a copy of the data locally?

What if the image skeleton screen could also get the image data in advance? Is it possible to try rendering images as well?

Now, the question is, is this still a skeleton screen? Another thing we can learn about skeleton screens is that any element that is not bound to a JS event can be considered skeleton.

People have beauty and ugliness. Why not a skeleton screen? So there’s going to be someone here again. You’re a data cache and lazy loader. Does the skeleton screen need that?

So, what is a skeleton screen? Is the essence of a skeleton screen to automatically generate a skeleton for your components? What kind of skeleton do you care? I have a performance monitoring platform, okay? The platform told me that my page-per-second rate had increased significantly.

So, the most important thing is that even though many people think front-end performance optimization is the same as the old four, you can still play the game. After all, the proof is in the pudding.

The snapshot

Snapshots are an interesting thing. For example, Tmall will generate a transaction snapshot for you when you place an order, and all subsequent processes will be subject to the data of the transaction snapshot to ensure that your money will not be spent more or less later. It’s normal to change prices when you compare them.

There is also a snapshot explanation. For example, a screenshot of a mobile phone can generate a picture of the page content seen by the current user and save it in an album.

Well, here’s one. Make a snapshot of your home page and back it up to native cache. Load that snapshot every time you come in. This snapshot is the index.html file that is stored in the native package’s local cache. Do you think it’s faster for the browser to access your index.html directly?

There’s going to be another bar. Why is this like SSR? SSR, the server will send the client a template string containing HTML, can be no style, can not js. But snapshots have style, like putting a picture over your home page. Do you think it’s faster to render an image that covers your home page, or to access an index.html?

pre-rendered

Let’s explain the nature of pre-rendering first. Prepare the following two points in advance:

  • index.html + js + css
  • data (JSON)

Here’s another picture.

Pictures from the network, if any infringement, please contact delete)

Combine the picture description, explain carefully again.

Pre-rendering is the preparation of the page before the user accesses the page. To put it simply, I store the content of the page out of sight before the user visits it, and then move the rendered content to where it can be seen when the user needs to see it.

Just to summarize a little bit.

  • The content of the page should be rendered before the user can officially visit it.
  • When the user officially visits, it simply loads the rendered content directly.

How to achieve it?

NSR(Native side rendering, client rendering)

Through the client (Native) for page structure splicing, and then realize the processing technology of page rendering.

Offline packages are required to provide templates and other resources (such as HTML, JS, and CSS). Preloading provides data, and pages are rendered on the client side by the V8 engine as a result of the data being changed by template functions.

  • preloadGet your data ready in advance. For example, the interface is cached before the user accesses it, and the resulting data is cached after the interface is called.

How does NSR work?

  1. The first is that the templates and data must be ready, so that all the resources for the page are ready when the user clicks the link to enter the page. As for how to do this, we can take a look.
  • Available offline
  • preload
  • The cache
  1. Because pages are dynamic and urls are static, we need to implement a mapping mechanism between pages and templates, usually many to one. This mechanism helps Native quickly locate templates that users need.

  2. Implement the local rendering service in the Native side. (This is a bit like SSR, details on SSR will wait for a follow-up article).

  3. After The NSR is done, nothing needs to be done to The front-end code, just to get The post-process ready. Post-processing refers to placing rendered pages outside of the viewable area.

The subtotal

Every company environment is different, and every technology solution does not necessarily need to be fully implemented. If you can achieve the performance standard by implementing some of them, there is no need to spend more money on the rest. In fact, webpack’s pre-rendering is a little more intuitive. The code is posted for you to look at, friends can also go to the previous article to see more details.

An example of code for Webpack to implement pre-rendering is as follows:// webpack.conf.js
var path = require('path')
var PrerenderSpaPlugin = require('prerender-spa-plugin')
module.exports = {
  // ...
  plugins: [
    new PrerenderSpaPlugin(
      // Where the compiled HTML needs to be stored
      path.join(__dirname, '.. /dist'),
      // Lists which routes need to be prerendered
      [ '/'.'/about'.'/contact'])]}Copy the code

To be continued

The next article should cover solutions to white screen and lag. Stay tuned.