Web Performance Fundamentals

Posted by Yanchao MURONG on 2021-10-30

Web Vitals

  • First Contentful Paint (FCP) - RESPONSE QUICK
  • Largest Contentful Paint (LCP) - GET TO THE POINT
  • Cumulative Layout Shift (CLS) - DON'T MOVE STUFF
  • First Contentful Paint (FID) - DON'T LOAD TOO MUCH
web-vitals

Google Chrome web vitals: https://github.com/GoogleChrome/web-vitals

Lighthouse

Lab data vs Field data https://www.lightest.app/

Performance Analytics

  • CLS is inversely correlated to Session Time
  • LCP is inversely correlated to Bounce Rate

Optimizing Metrics

Improving FCP

  • Sized Correctly (Hardware, VM, network, etc)
  • Minimal Processing
  • Network Bandwidth (compression, cdn...)

Improving LCP

Defer resources until later

LCP.png
  • async vs defer

defer will defer js execution after LCP

asyncdefer.png
  • Lazy loading

We could use IntersectionObserver to detect when an element becomes visible in window and load it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var lazyObserver = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
var el = entry.target;
load(el);
lazyObserver.unobserve(el);
}
});
});

function load(el) {
var src = el.getAttribute("data-src");
var srcset = el.getAttribute("data-srcset");
if (src) { el.setAttribute("src", src); }
if (srcset) { el.setAttribute("srcset", srcset); }
el.removeAttribute("data-src");
el.removeAttribute("data-srcset");
}

Responsive Images

Let image downloads based on the viewport size.

responsiveimages.png

HTTP2, Caching, and Pre-loading

  1. HTTP2 allows us to reuse the connections, yet not all servers support them
  2. Caching
    1
    2
    3
    cache-control: max-age=600
    expires: Wed, 20 Jan 2021 03:13:21 GMT
    etag: "600a4af-c96f"
  3. Preloading Use annotations of preconnect and preload to preload CSS fonts => reduce the time between FCP and LCP

Improving CLS practice

Be careful with relative position and prefer reserve space for large image