This is the fifth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

Use PRPL mode to apply instant loading

  • Preload key resources
  • Render the initial route as soon as possible
  • Cache resources based on business policies
  • The remaining routes and non-critical assets are lazily loaded

The font to optimize

  • Avoid invisible text during font loading

Fonts are usually large files that take a while to load, and the browser mechanism is that if you import a font with @font-face, the text will not be displayed until the font file is requested. If the font file is larger than 3s and not ready, the text will be displayed using the system default font. For this non-flicker effect, we need a swap property.

@font-face {
	font-family: 'SourceHanSansCN-Bold';
	src: url('./fonts/SourceHanSansCN-Bold.otf');
	font-display: swap;
}
Copy the code

Font-display Supported values:

 font-display: auto; /* or block, swap, fallback, optional */
Copy the code

Preloads webFont resources

You can use to trigger webFONT requests early in critical path rendering so that you don’t have to wait for csSOM to be created.

Chrome provides us with a font loading API that feels like we might need it.

var font = new FontFace("Awesome Font"."url(/fonts/awesome.woff2)", {
  style: 'normal'.unicodeRange: 'U+000-5FF'.weight: '400'
});

// don't wait for the render tree, initiate an immediate fetch!
font.load().then(function() {
  // apply the font (which may re-render text and cause a page reflow)
  // after the font has finished downloading
  document.fonts.add(font);
  document.body.style.fontFamily = "Awesome Font, serif";

  // OR... by default the content is hidden,
  // and it's rendered after the font is available
  var content = document.getElementById("content");
  content.style.visibility = "visible";

  // OR... apply your own render strategy here...
});
Copy the code
The cache
  1. Font resources are usually static resources that don’t update very often and are ideal for using HTTP caching. HTTP caching is a best practice for font resources, and other browser caches are generally not suitable for font resources.

Reduce the font

  1. The server is configured with Gzip compression

Third Party services

  • Select a stable, secure, and high-performance third-party resource service.
  • Periodically review and eliminate redundant third-party scripts.

What are the key render paths

  • Optimizing the Render path
    • The content related to the current user action is displayed preferentially.
  • What are the key render paths
    • A series of steps that a browser must take to convert HTML, CSS, and JS into an actual running website.

JavaScript to add interaction

  • Our script is executed wherever it is inserted, and when the HTML parser encounters aScript tag, it pauses building the DOM, handing control of the DOM tree to the JavaScript engine (because JavaScript has permission to manipulate the DOM tree). When the JavaScript engine is finished running, the browser will resume the DOM build from where it left off. If a script has a SRC attribute, then the browser parsing to the script tag must stop and wait for the script to be fetched from disk, cache, or a remote server, potentially adding unequal delays to the critical rendering path.
  • Not all resources are critical to providing a first draw quickly. In fact, when we talk about the first key render path, we usually talk about HTML, CSS, JS. Images do not prevent the first rendering of the page.

Optimizing JavaScript execution

  1. For animation effects, avoid using setTimeout or setInterval and use requestAnimationFrame instead.
  2. Move long-running JavaScript from the main thread to the Web Worker.
  3. Use microtasks to perform DOM changes to multiple frames.
  4. Use Chrome DevTools’s JavaScript profiler to assess the impact of JavaScript.
  5. To minimize the browser’s rendering of web pages, defer any non-essential scripts (that is, scripts that are not critical to the first rendering of visible content).
  6. Avoid running long-running JavaScript, which prevents browsers from building DOM, CSSOM, and rendering web pages. If you need to run long serialized code, consider time slicing and task scheduling (react framework)
  • We want to perform your animation work at a time that is appropriate for the browser. And run your program at the start of a frame.
/** * If run as a requestAnimationFrame callback, this * will be run at the start of the frame. */
function updateScreen(time) {
  // Make visual updates here.
}

requestAnimationFrame(updateScreen);
Copy the code

Optimizing CSS

  • Coverage analysis
    • Green: Content required by the browser to render visible content
    • Red: Content that is not immediately visible
  1. Make sure that any non-essential CSS is marked as non-critical resources (such as printing and other media queries, media attributes distinguish).
  2. Reduce the size and number of CSS and shorten the transfer time
  3. The CSS needs to be placed inside the head tag so that the browser can find the link tag and send CSS requests as soon as possible.
  4. Avoid using the CSS @import directive to import rules from another stylesheet. They increase the number of roundtrips in the critical path, and the imported CSS resources are not discovered until the CSS style sheet with the @import rule has been received and parsed.
  5. The key CSS is inlined into the HTML document, which does not increase the number of round trips in the critical path. If done properly, the number of critical path round trips can be significantly reduced.
    1. Disadvantages of inlining: If you have a lot of CSS inlined, it can delay the transfer of the rest of the HTML document, and it directly eliminates browser caching. The HTML document should be under 14KB.
  6. link rel="preload" as="style"Asynchronous request stylesheets

Optimize CSS selectors

  1. Reduce the complexity of the selector; Use class-centric methods, such as BEM.
    1. Avoid cascading CSS selectors
  2. Reduce the number of elements whose styles must be computed.
    1. Avoid. Box :nth-last-child(-n+1) selector.

Optimize layout (rearrange) operations

A frame of rendering steps: JavaScript execution = “Calculate style => Start layout => Start repainting => Composite layer

  1. Avoid layout operations whenever possible

    1. When you change the style, the browser checks to see if the change requires calculating the layout and updating the render tree. Changes to “geometric attributes” such as width, height, left, or top require layout calculations.

    2. Reordering almost always affects the entire document. If you have a large number of elements, it will take a long time to figure out the position and size of all the elements.

  2. Use Flexbox instead of the earlier layout model

Optimized drawing operation

  1. Do use transform and opacity property changes for animation.
    1. Changing any property other than transform or opacity always triggers a drawing.
  2. Reduce the area of drawing by elevating layers and choreographing animations
  3. The best way to create a new layer is to usewill-changeCSS properties. This method works on Chrome, Opera, and Firefox and passestransformWill create a new synthesizer layer. A word of caution: Don’t create too many layers, because each layer requires memory and administrative overhead.
  • The transform and opacity

    The best performing version of the pixel pipeline avoids layout and drawing and only requires compositing changes (these are currently the only two properties that work): The important thing to note when using transform and opacity is that the element where you change these properties should be in its own synthesizer layer. To make a layer, you must promote elements.

Ascend to one’s own level

.moving-element {
  will-change: transform;
}
Copy the code