Optimizing Web Vitals: What , Why and How!

In the world of web, speed thrills and lets you chill!

You came up with a business idea and then decided to bring it live. You hired bunch of developers and transmuted your mental imagination into an online foot print of your product via a website. All good. The only problem was users where not interested in buying anything from your site. Whaaaat? Whyyyy? You did everything but still were seeing minimal customer conversions. So you decided to audit your website. Boom! You know the culprit now! Performance and Speed.

The above scenario is a typical problem faced by new businesses or even the existing businesses running outdated websites and not focusing on the web vitals.

Lets try to understand the problem statement and then an optimal solution for the same.

The What part: Customers are our top priority. We all want loyal and consistent customers. But customers have little patience. If your page takes more than 3–4 seconds to load, you would have already lost 45–65% of the potential customers. For a product, there are multiple alternatives available in the market to a customer. So a more load time means customer opening a new tab and navigating to your competitors website i.e. high bounce rate. Or worst, they would simply rate your business single star just because it didn't load for him/her.

In order to avoid all such scenarios we must code our website in such a way that its performance is at its peak and the site is up-to date with the current web standards. Cutting to the chase , we have 4 major web vitals to focus on:

  1. FCP (First Contentful Paint): measures how long it takes the browser to render the first piece of DOM content after a user navigates to your page.
  2. LCP (Largest Contentful Paint): measures loading performance. To provide a good user experience, LCP should occur within 2.5 seconds of when the page first starts loading.
  3. FID (First Input Delay): measures interactivity. To provide a good user experience, pages should have a FID of 100 milliseconds or less.
  4. CLS ( Cumulative Layout Shift): measures visual stability. To provide a good user experience, pages should maintain a CLS of 0.1. or less.

The Why Part: Now we know about the web vitals, it is important to understand why we need to optimize each one of them.

Lets take Al Jazeera website as an example to understand each metrics. Once you open Al Jazeera website go to dev tools->Lighthouse and audit the page

Auditing might take few minutes
  1. FCP: Once the page starts loading we first see only few elements of the website and later the other elements load. As we can see in case of our Al Jazeera website, the first screen is blank and the second screen loads few elements. This screen is our FCP. A higher FCP time means a drop in users as the wait time to see the first screen increases. Hence its inevitable to not optimize FCP.
Second screen is when FCP loads

2. LCP: Once we have seen the FCP, the other elements load and we finally see the website painted with almost all the other elements of the page. This stage is the LCP. In our example we can consider the last screen as when the LCP happened. Minimum LCP is important because of the same reason as FCP . Additionally once the LCP has happened, the user can see more info on the website hence more the retention.

The last screen can be considered as the LCP

3. FID: Suppose we have a button in our website . The FID denotes the time it takes for that button to become clickable. The more the FID , the more unresponsive the page looks resulting in an increased bounce rate.

4. CLS: Sometimes we might have observed that the when the website loads fully, there’s a shift in some elements. i.e. they get pushed down because some other element was visible at a later point above it. This is called CLS and it is not at all a good idea to have elements moving on the screen. This is because user might try to click something in that block while that block suffered CLS and got pushed below. Its really annoying.

The How Part: So now we understand the what and why part let us try to figure out how we can optimize each one of them individually.

  1. FCP: There are multiple ways in which we can optimize the FCP. Lets discuss them :

a. One way is to have quick servers with minimum per packet size and a higher n/w bandwidth so that packets are transferred quickly. But this is something which should be done during the architecture phase and hence we don't have much control over them.

b. Another approach is create our index.html file in such a way that it contains the basic skeleton layout of our page and instead of seeing a black screen the user sees the skeleton loading. Loading a skeleton is still better than showing blank screen.

c. Yet another way is to compress the CSS and JS that we are shipping through the network packet. Few of the best optimization techniques are Brotli and gzip compression with a fallback to the default compression. Compression decreases packet size significantly.

d. Eliminate Render-Blocking Resources : A webpage is rendered by the browser after putting together many elements such as HTML, CSS stylesheets, JavaScript scripts, and HTML imports. When the user requests for a webpage, the browser would’ve received the HTML content already, but will still be waiting for all the other resources to be loaded before rendering the page. As a result, they are called render blocking resources.

e. Inline Critical resources: First, identify critical scripts and styles that are necessary to render the FCP of your webpage. Once you’ve identified the critical scripts, you need to remove them from the render-blocking resource and then inline them inside your HTML page with <script> and <style> tags.

2. LCP: Again there are multiple ways to optimize LCP

a. Use of async and defer: once we have loaded our critical resources for FCP, we can delay the other non- critical resources using async or defer attributes to manipulate the order in which scripts are loaded.

b. Lazy load images: The images that are not in the first fold of the screen can be loaded later using the lazy load techniques available.

c. Graceful image loading: In slower networks, it might take a lot of time for images to load . Here we can make use of a technique called graceful loading where we first load a blurry image and then gradually load the full image. This is extensively used by Medium website as well.

d. Use of sprite images: Each image requires a separate network call . We can optimize this by creating a sprite image which contains all the images required for our page . This single sprite image requires a single network call hence optimizing the network requests. Later these sprite images can be used by the help of positions .

e. Use of HTTP2: Nowadays most of the websites use HTTP2. One of the major advantage of this is that the connection can be reused so each time 3-way handshake is not required.

3. FID: First Input Delay is based on the psychology of wait. Once the user sees the page, the default behavior is to start interacting with the page. If the FID is high, it will leave the user anxious.

To measure FID in JavaScript, we can use the Event Timing API. The following example shows how to create a PerformanceObserver that listens for first-input entries and logs them to the console:

new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
const delay = entry.processingStart - entry.startTime;
console.log('FID candidate:', delay, entry);
}).observe({type: 'first-input', buffered: true});

In the above example, the first-input entry's delay value is measured by taking the delta between the entry's startTime and processingStart timestamps. In most cases this will be the FID value; however, not all first-input entries are valid for measuring FID.

To optimize FID, along with the above mentioned techniques we can use preload or preconnect to load important JS so that the site is responsive by the time the LCP is done.

4. CLS: Our main goal here is to not allow the elements to move during the loading phase. For this we need to somehow fix the positions of the elements in the first fold, preferably. We can use the width and height attribute for divs or images to handle this. The width and height here are aspect ratios basically i.e. we don't write width=’200px’or width=’20%’ , rather we simply assign width=’200’ as the aspect ratio.

All these techniques combined, end up optimizing the web vitals thus leading to a higher page score and ultimately a better page rank!

Web developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store