Frontend Masters Boost RSS Feed https://frontendmasters.com/blog Helping Your Journey to Senior Developer Mon, 10 Feb 2025 14:33:56 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.3 225069128 Optimizing Images for Web Performance https://frontendmasters.com/blog/optimizing-images-for-web-performance/ https://frontendmasters.com/blog/optimizing-images-for-web-performance/#comments Mon, 10 Feb 2025 14:33:55 +0000 https://frontendmasters.com/blog/?p=5153 Images make websites look great, but they’re also the biggest performance bottleneck. They add huge file sizes, delay Largest Contentful Paint (LCP), and can even mess with Cumulative Layout Shift (CLS) if they aren’t handled properly. And while developers are quick to optimize JavaScript and CSS, images are often ignored—despite being the heaviest assets on most pages.

So, how do we make images fast, responsive, and efficient? Here’s how:

Choose the Right Image Format

The format of an image has a massive impact on its size and loading speed. Picking the wrong one can easily double or triple your image payload. Check out this illustration: 

Size comparison of images in formats

To the user, it’s the exact same image, but the browser has to download 2x-10x more data depending on the format you pick.

Have a look at this photograph: 

Size comparison of photo in formats

Photographs are quite a bit more complex than illustrations (usually), and the best formats can change. Notice how JPG is smaller than PNG this time, but modern formats like WebP and AVIF are still way smaller.

  • JPG – Best for photos with lots of colors and gradients. Uses lossy compression to keep file sizes small.
  • PNG – Best for graphics, logos, and transparency. Uses lossless compression, but files can be huge.
  • WebP – A modern format that’s often smaller than JPG and PNG while keeping quality high.
  • AVIF – Even better compression than WebP, but not universally supported yet.

good rule of thumbJPG for photos, PNG for graphics, and use WebP or AVIF where possible for modern browsers.

Use Responsive Images

Not all users have the same screen size, so why serve the same massive image to everyone? Responsive images let you deliver the right image size based on the user’s device, reducing unnecessary downloads and improving load times.

Instead of a single <img> tag, try using a <picture> with the srcset and sizes attributes to tell the browser which image to load:

In this example, any screen less than 1400px wide will use an image from the srcset that is at least 100% of the viewport’s width. So if the screen is 1100px wide, the browser will select and download the hero-desktop-1024 version. This automatically scales images to match different devices, saving bandwidth and improving loading speed for smaller screens.

Lazy-Load Below the Fold

One of the worst offenders for slow performance? Loading every image on the page at once—even ones that aren’t visible. This is where lazy-loading comes in. Adding loading="lazy" to an <img> prevents it from downloading until it’s about to be seen.

<img 
  src="downpage-callout.jpg" 
  loading="lazy" 
  height="300"
  width="300"
>  

It’s very important to specify the height and width attributes of images, especially if they are going to be lazy-loaded. Setting these dimensions let’s the browser reserve space in your layout and prevent layout shifts when the content loads. For more about layout shifts and how to prevent them, check out this deep dive on Cumulative Layout Shift.

For images that are critical for rendering, like your LCP element, you should override lazy-loading with fetchpriority="high". This tells the browser to load it ASAP.

<img 
  src="downpage-callout.jpg" 
  fetchpriority="high" 
  height="300" 
  width="300"
>

Serve Images from a CDN

Content Delivery Network (CDN) stores images in multiple locations worldwide, so they load from the nearest server instead of your origin. This speeds up delivery and reduces bandwidth costs.

CDNs use modern HTTP Protocols

Most CDNs will also speed up your images by serving them with modern protocols like HTTP/3, which has significant performance improvements over both HTTP/1 and HTTP/2. Check out this case study on HTTP/3 performance.

HTTP Caching headers

Users always have to download an image at least once, but HTTP caching headers can help repeat visitors load them much faster. HTTP Caching headers instruct the browser to hold onto the image and use it again, rather than asking for it from the CDN again on the next visit. Here’s an example:

Cache-Control: public, max-age=31536000, immutable

This tells the browser that this image won’t change, and that it can be kept locally for 1 year without needing to be requested again. Caching isn’t just for images—it speeds up all static assets. If you’re not sure if your caching is set up correctly, there’s a full guide on HTTP caching that explains how to check and optimize it.

Wrapping Up

Images are one of the biggest opportunities for improving performance. By choosing the right format, compressing efficiently, lazy-loading, and leveraging CDNs with modern protocols, you can massively speed up your site.

If you’re looking for more image optimization tips, with detailed breakdown and real-world examples, check out the complete guide to optimizing website images.

]]>
https://frontendmasters.com/blog/optimizing-images-for-web-performance/feed/ 6 5153
Mastering Interaction to Next Paint (INP) https://frontendmasters.com/blog/mastering-interaction-to-next-paint-inp/ https://frontendmasters.com/blog/mastering-interaction-to-next-paint-inp/#respond Tue, 05 Nov 2024 15:20:28 +0000 https://frontendmasters.com/blog/?p=4318 The web keeps changing—and so do the ways we measure web performance. Google recently updated its Core Web Vitals metrics, dropping First Input Delay (FID) in favor of a new and improved interaction metric: Interaction to Next Paint (INP).

FID was a step in the right direction, measuring how quickly a site responds to the first interaction. But it fell short by focusing only on that initial action, leaving out every click and type that follows. It also emphasized blocking time over total processing time, missing the real story behind user experience.

How is INP different? We’ll dive into exactly what it’s measuring, how to diagnose it, and, most importantly, how to fix it so your website interactions feel fast and responsive.

What “Interaction to Next Paint” Measures

INP monitors every interaction a user makes with a page—whether it’s a click, tap, or key press. It measures the time it takes for each of these interactions to trigger a visible change, or “next paint,” on the screen, capturing every millisecond from receiving the input to updating the display.

Over the lifetime of a page, there should (hopefully) be lots of user interactions. Your INP score is determined by the “worst” interaction on the page—the one with the longest delay until a response.

It may sound harsh, but it’s realistic. If just one interaction lags, that’s what users remember. By focusing on the most significant delays, INP spotlights the interactions that need the most attention to create a truly responsive experience.

To hit a good INP score, a page needs to respond to every interaction in under 200 milliseconds.

Why INP Matters

INP directly measures a website’s interactivity—how responsive the site feels to users as they interact. We’ve all had that frustrating experience of clicking a button, only to have nothing happen right away. Suddenly, you’re wondering if the click registered or if you need to try again. That’s the feeling of poor interactivity.

When interactions lag, users feel like the site is “slow,” “laggy,” or even “broken.” It’s a surefire way to frustrate users, lose engagement, and damage credibility.

And if that’s not enough, INP is one of Google’s Core Web Vitals and a factor in SEO rankings. Google doesn’t want to send search traffic to laggy sites, so it penalizes pages that fail their INP scores.

Understanding INP Measurement in Detail

Before we dive into tactics to fix INP, it’s important to understand how INP is measured. If you’re looking for even more details, check out this deep dive on Interaction to Next Paint.

Interactions

INP measures the response time for all discrete interactions—like clicks, taps, drags, and key presses—that users make while on the page. These actions initiate user commands and usually lead to some form of visual feedback, so tracking them is essential for accurately gauging a site’s interactivity.

One common action that doesn’t factor into INP, however, is scrolling. Scrolling is typically continuous rather than discrete and has its own performance considerations outside of INP’s scope.

The INP Measurement Window

INP measures everything that happens between a user interaction and the next paint event, and a lot can occur in that window. Here’s how it breaks down:

  1. Input Delay: When the interaction event is triggered, the browser may already be busy, for instance, executing an obnoxious amount of JavaScript. Since JavaScript can block the main thread, the browser has to wait until it’s finished before it can even start processing the interaction. This waiting period is the input delay.
  2. Event Handling: Once the main thread is free, the browser can dispatch the event to any associated event handlers—and there could be quite a few. Each event handler needs to be called and completed before moving forward.
  3. Rendering: After all JavaScript is done executing, the browser can calculate what changed in the DOM, update elements and layout, and finally paint the next frame to the viewport.

INP and Long Animation Frames (LoAF)

INP is closely related to Long Animation Frames (LoAF), as both metrics capture user responsiveness and visual feedback. LoAF measures the time between paint events, regardless of whether an interaction happened, indicating if the browser may have felt “frozen” to the user.

A slow INP is often accompanied by a Long Animation Frame, which can provide more details on the scripts or activities causing delays. For more information, check out this detailed guide on Long Animation Frames.

How to Improve Your INP Score

Improving your INP score means reducing the time users wait for visible feedback after they interact. Here are some strategies to make sure your site responds quickly:

  • Yield to the Main Thread: Avoid monopolizing the main thread with long-running tasks. When you block the main thread, user interactions get stuck waiting. Breaking up heavy tasks with setTimeout or requestAnimationFrame can reduce delays and keep the main thread open for user input.
  • Optimize JavaScript: Large JavaScript bundles are often the main culprit for interaction delays. Reduce bundle size through code-splitting, lazy-loading, and minifying to improve response times. Only load what’s necessary at each stage of the user journey.
  • Reduce Long Animation Frames (LoAF): A poor INP score often coincides with Long Animation Frames, so addressing LoAF can directly improve INP. This includes avoiding intensive calculations during animations and syncing visuals with the browser’s rendering cycle.

Implementing these strategies can bring down your INP score, keeping interactions responsive and making your site feel faster and more polished.

Example INP Fix

Let’s have a look at a specific example. Below is a CodePen with a simple form that includes a JavaScript event handler triggered each time the user types, changing the class on the button.

In this example, the JavaScript handler also calls a slow function, renderSearch, each time the event fires. Since renderSearch is part of the event handler, it slows down the entire animation frame and causes both LoAF and INP issues by blocking the main thread for too long.

Here’s how to fix it:

In our fix, we wrapped the event handler in requestAnimationFrame, which delays execution until just before the next paint. Then, we adjust the button class immediately, while the heavier work in renderSearch is delayed with setTimeout so it won’t execute until after the paint is complete. This approach prioritizes responsiveness and keeps user feedback snappy by yielding to the main thread.

Wrapping Up

Interaction to Next Paint (INP) gives us a more complete view of web interactivity by tracking every user interaction throughout a page’s lifecycle. With INP replacing FID as a Core Web Vital, optimizing for it has never been more critical. A strong INP score not only improves user satisfaction by keeping interactions fast and responsive but also boosts your SEO by aligning with Google’s performance standards.

By implementing strategies like yielding to the main thread, optimizing JavaScript, and addressing Long Animation Frames, you can create a smoother, more responsive experience for users. As you tackle these improvements, Real User Monitoring tools like Request Metrics can help you track INP and other Core Web Vitals in real-time, showing exactly where delays are occurring and how effective your fixes are.

Making your website interactive and smooth isn’t just about performance scores—it’s about ensuring users have a seamless experience on your site. With INP insights and a focus on responsiveness, you can keep users engaged, happy, and coming back for more.

]]>
https://frontendmasters.com/blog/mastering-interaction-to-next-paint-inp/feed/ 0 4318