Duong Hoang Nam

Search Articles

Find AI, technology, and programming guides

Press Esc to closeFull Search Page →
Technology

How I Reached 99/100 on PageSpeed Mobile with Astro and WebP

Learn how an Astro website reached 99/100 on PageSpeed Mobile using Sharp, responsive WebP, srcset, smart image loading, and a CMS-safe build pipeline.

By Duong Hoang Nam
How I Reached 99/100 on PageSpeed Mobile with Astro and WebP

The fastest website is not necessarily the one with the fewest images. It is the one that sends the right image, in the right format, at the right time.

On October 23, 2026, I compared two mobile PageSpeed Insights snapshots of DuongHoangNam.com, my Astro-based technology website. An earlier run reported a 4.0-second Speed Index. A later run, after responsive-logo improvements, reported a 2.6-second Speed Index and a 99/100 mobile Performance score.

The later report also showed 1.5-second Largest Contentful Paint (LCP), 0 ms Total Blocking Time (TBT), and zero Cumulative Layout Shift (CLS). These are individual Lighthouse lab measurements, not long-term field-data guarantees. The two runs were not a controlled A/B test, so the 35% Speed Index difference cannot be attributed exclusively to one code change.

Still, the investigation revealed a useful, repeatable engineering problem: our image build pipeline generated responsive WebP files, but the header and footer logos were still requesting their original PNG files. This article shows how to find that gap and fix it without breaking a CMS, a theme switcher, or image SEO.

The result at a glance

Metric Earlier mobile snapshot Later mobile snapshot
Speed Index 4.0 s 2.6 s
Estimated opportunity: improve image delivery ~40 KiB ~13 KiB
Mobile Performance score Not recorded here 99/100
LCP Not recorded here 1.5 s
TBT Not recorded here 0 ms
CLS Not recorded here 0

What changed? We made the existing responsive image system available to the site’s light-mode and dark-mode wordmark logos. We did not remove content, disable analytics, or blindly reduce image quality. Other factors may also have influenced the scores between runs.

Illustrated summary of DuongHoangNam.com PageSpeed Mobile results: Performance 100, Accessibility 100, Best Practices 100 and SEO 100

Illustrated summary of DuongHoangNam.com PageSpeed Mobile results: Performance 99, Accessibility 100, Best Practices 100 and SEO 100

Figure 1. Illustrated summary based on a PageSpeed Insights mobile test of DuongHoangNam.com on October 23, 2026.

1. Understand the architecture before optimizing

This website uses a fairly common static-site setup:

Decap CMS
  └─ uploads original images to GitHub
       └─ public/images/uploads/
            └─ Astro generates static HTML
                 └─ Sharp creates responsive WebP variants
                      └─ dist/images/optimized/
                           └─ Cloudflare Pages deploys the dist folder

Astro does not automatically optimize files in public/ through its built-in image pipeline. That matters for CMS-driven websites because uploads often arrive as normal public files rather than assets imported from src/.

Our solution was a small build-time image pipeline, paired with an Astro component that outputs responsive image markup. This keeps the original asset available as a fallback and avoids requiring content editors to manage multiple sizes manually.

2. Start with PageSpeed, then inspect the actual request

In the earlier mobile report, the Improve image delivery audit flagged the light-mode wordmark PNG. It was approximately 28 KiB, despite being displayed at a much smaller width. The report estimated a substantial saving for that logo alone.

A common mistake is to see an optimized image directory on disk and assume browsers are using it. They may not be.

Open Chrome DevTools, go to Network, select Img, reload the page, and inspect:

  1. Request URL: is the browser requesting /images/uploads/logo-wordmark-light-cms.png or a generated /images/optimized/...webp file?
  2. Type: is the response actually image/webp?
  3. Transferred size: does the chosen image match the small displayed logo?
  4. Viewport and device pixel ratio: does the selected file have enough resolution without being unnecessarily large?

This step turns “we generate WebP” into the verifiable statement “the browser downloaded an appropriately sized WebP.”

3. Generate WebP variants with Sharp

If your Astro site uses files in public/images/uploads/, you can create optimized images after the static build. Install Sharp:

npm install --save-dev sharp

Here is a reduced version of the approach used on this site. It generates multiple widths, avoids upscaling, respects EXIF rotation, and uses a content hash to keep file names stable until an image changes.

// scripts/optimize-images.mjs
import { createHash } from 'node:crypto';
import { readdir, readFile, mkdir } from 'node:fs/promises';
import path from 'node:path';
import sharp from 'sharp';

const INPUT = path.resolve('public/images/uploads');
const OUTPUT = path.resolve('dist/images/optimized');
const WIDTHS = [160, 320, 480, 640, 672, 768, 1200, 1600];
const SUPPORTED = /\.(?:jpe?g|png|webp)$/i;

async function* walk(folder) {
  let entries;
  try {
    entries = await readdir(folder, { withFileTypes: true });
  } catch (error) {
    if (error.code === 'ENOENT') return;
    throw error;
  }

  for (const entry of entries) {
    const file = path.join(folder, entry.name);
    if (entry.isDirectory()) yield* walk(file);
    else if (entry.isFile() && SUPPORTED.test(entry.name)) yield file;
  }
}

for await (const file of walk(INPUT)) {
  const bytes = await readFile(file);
  const metadata = await sharp(bytes).metadata();
  const originalWidth = [5, 6, 7, 8].includes(metadata.orientation ?? 1)
    ? metadata.height
    : metadata.width;
  if (!originalWidth) continue;

  const hash = createHash('sha256').update(bytes).digest('hex').slice(0, 12);
  const relative = path.relative(INPUT, file);
  const parsed = path.parse(relative);
  const outputFolder = path.join(OUTPUT, parsed.dir);
  await mkdir(outputFolder, { recursive: true });

  for (const width of WIDTHS.filter((w) => w <= originalWidth)) {
    await sharp(bytes)
      .rotate()
      .resize({ width, withoutEnlargement: true })
      .webp({ quality: 80, effort: 4 })
      .toFile(path.join(outputFolder, `${parsed.name}-${hash}-w${width}.webp`));
  }
}

Why these choices?

  • Several widths: A small card, a mobile article image, and a full-width desktop image should not download the same file.
  • Content hash: Updating an upload changes the generated URL, which makes cache invalidation easier.
  • No enlargement: A 300-pixel source cannot be made genuinely sharper by exporting it at 1,200 pixels.
  • Quality 80: A reasonable starting point, not a universal rule. Validate screenshots containing fine text visually.

The output step needs to run after astro build because it writes into dist/.

4. Connect generated images to the HTML

Generating variants is only half of the job. The browser needs to discover them through srcset and sizes.

Suppose the build creates:

/images/optimized/logo-wordmark-light-cms-HASH-w160.webp
/images/optimized/logo-wordmark-light-cms-HASH-w320.webp
/images/optimized/logo-wordmark-light-cms-HASH-w480.webp

A responsive element can then look like this:

<picture>
  <source
    type="image/webp"
    srcset="/images/optimized/logo-HASH-w160.webp 160w,
            /images/optimized/logo-HASH-w320.webp 320w,
            /images/optimized/logo-HASH-w480.webp 480w"
    sizes="(max-width: 640px) 170px, 210px"
  />
  <img
    src="/images/uploads/logo-wordmark-light-cms.png"
    alt="Duong Hoang Nam"
    width="1160"
    height="150"
    decoding="async"
  />
</picture>

The HASH values above are illustrative. A production implementation must calculate filenames from the same source bytes and hashing rule as the Sharp script.

The browser uses sizes to estimate how wide the image will appear, then chooses an appropriate candidate from srcset, accounting for device pixel ratio. Keep the original src as a fallback; Google also recommends doing so for image discoverability and compatibility.

In our Astro codebase, a getCmsSrcSet(src) helper handles path validation, source-image inspection, hashing, and building these strings automatically. The reusable ResponsiveCmsImage.astro component then renders the <picture>, <source>, and <img> markup, so authors do not need to handwrite hashed filenames.

Important: Because the helper returns the original image in development mode, use npm run build followed by npm run preview when testing the optimized output. astro dev is not a valid test of this particular post-build optimization pipeline.

5. Optimize light and dark logos without changing the design

This was the most relevant improvement for our site. Decap CMS stores two logo URLs:

  • logo for Light Mode, with dark navy lettering.
  • logoDark for Dark Mode, with light lettering against a navy background.

Previously, the Header and Footer used ordinary image tags pointing directly to those PNG URLs. The optimized WebP files existed, but the logos did not use them.

The fix was to call the existing helper for both theme assets and render a responsive <picture> for each:

---
import { getCmsSrcSet } from '../lib/cms-images';

const logoLight = settings.logo?.trim() || '';
const logoDark = settings.logoDark?.trim() || logoLight;
const lightSet = logoLight ? await getCmsSrcSet(logoLight) : undefined;
const darkSet = logoDark ? await getCmsSrcSet(logoDark) : undefined;
const logoSizes = '(max-width: 640px) 170px, 210px';
---

{logoLight && (
  <>
    <picture class="block dark:hidden">
      {lightSet && <source type="image/webp" srcset={lightSet} sizes={logoSizes} />}
      <img src={logoLight} alt="Duong Hoang Nam" width="1160" height="150"
           class="h-auto max-h-10 max-w-[210px] object-contain" />
    </picture>
    <picture class="hidden dark:block">
      {darkSet && <source type="image/webp" srcset={darkSet} sizes={logoSizes} />}
      <img src={logoDark} alt="" aria-hidden="true" width="1160" height="150"
           class="h-auto max-h-10 max-w-[210px] object-contain" />
    </picture>
  </>
)}

This is a focused illustration, not a drop-in replacement for every site’s Header. The settings object must already be available in the Astro frontmatter; adapt the CSS dimensions to your actual layout. For our actual site, we also preserved the existing responsive Header sizing, navigation, and footer structure.

A practical warning: a manual theme toggle based on an HTML .dark class is not always equivalent to the user’s system prefers-color-scheme. Do not rely solely on <source media="(prefers-color-scheme: dark)"> if your theme toggle can override the system preference.

Finally, inspect the Network panel when switching themes. Multiple image elements can sometimes trigger unexpected requests depending on markup and styles. Performance must be verified, not assumed.

6. Prioritize visible images without making every image urgent

Images near the top of a page may influence LCP. Images far below the initial viewport usually do not need to load immediately.

Our article cards make that distinction:

<ResponsiveCmsImage
  src={post.data.image}
  alt={post.data.title}
  width={1200}
  height={675}
  loading={priority ? 'eager' : 'lazy'}
  fetchpriority={priority ? 'high' : undefined}
  sizes="(max-width: 767px) calc(100vw - 40px),
         (max-width: 1023px) calc(50vw - 34px),
         (max-width: 1279px) calc(33.333vw - 32px), 395px"
  class="aspect-video w-full object-cover"
/>

Do not mark every image as high priority. If a hero image is the likely LCP element, keep it discoverable in the initial HTML and avoid lazy loading it. For below-the-fold article images, lazy loading helps save bandwidth.

Keep explicit width and height attributes, or another reliable aspect-ratio reservation, to prevent layout shifts.

7. Put the steps in the correct build order

For a static Astro site with post-build image generation, the build command can be:

{
  "scripts": {
    "build": "astro build && node scripts/optimize-images.mjs && pagefind --site dist"
  }
}

Then check your local production output:

npm run build
npm run preview

For a Windows PowerShell setup that restricts execution of npm.ps1, the equivalent commands are npm.cmd run build and npm.cmd run preview.

Make sure the generated dist/images/optimized/ files are included in the deployed output directory. If you publish only dist/ from the first build step without running the optimization script, the HTML can reference missing files.

8. Validate with three separate checks

Check A — Source code: View the rendered HTML. Confirm each relevant image has a WebP <source> and a valid original fallback.

Check B — Network requests: On a narrow mobile viewport, refresh with DevTools open. Confirm the chosen file is from /images/optimized/, responds successfully, and has a sensible transfer size.

Check C — Real measurements: Run PageSpeed Insights several times after deployment, compare the same URL and device mode, and then check Google Search Console → Core Web Vitals when enough field data becomes available.

The three primary Core Web Vitals are LCP, Interaction to Next Paint (INP), and CLS. As reference targets, Google classifies LCP at or below 2.5 seconds, INP at or below 200 milliseconds, and CLS at or below 0.1 as good when assessed at the 75th percentile of real-world visits. TBT from Lighthouse is useful lab data, but it does not replace field INP.

A single score of 99 is encouraging; it is not evidence that every visit, page, or device has a score of 99.

9. Common mistakes that waste time

Mistake Better approach
Generating WebP files but still linking to PNG originals Inspect the browser’s requested URL and add srcset to the component
Assuming images in Astro public/ are automatically transformed Use Astro’s supported asset pipeline or an explicit CMS image pipeline
Lazy-loading the hero/LCP image Use eager loading for the likely LCP image and lazy loading below the fold
Using sizes="100vw" for a narrow logo or card Describe the actual rendered width at each breakpoint
Compressing all images aggressively Compare screenshots and text-heavy graphics visually
Supporting two themes with one low-contrast logo Provide separate light and dark assets
Testing only with astro dev Test the exact production build and its generated images
Judging success from one Lighthouse score Use repeatable tests and monitor field Core Web Vitals

10. What I would improve next

Once the logo issue is solved, the best next improvements are content-related, not a desperate attempt to move from 99 to 100:

  1. Add real screenshots and architecture diagrams to technical tutorials where they help readers follow a step.
  2. Give each screenshot descriptive alternative text and a meaningful filename.
  3. Check whether images embedded directly in Markdown use the responsive image pipeline; a custom Astro component does not automatically transform every Markdown <img>.
  4. Test a long article page, not just the homepage. A page with several screenshots, code blocks, and embedded tools has different performance characteristics.
  5. Monitor field Core Web Vitals over time before tuning noncritical third-party scripts or rewriting small CSS files.

The central lesson: optimize the bytes the browser actually downloads. A sophisticated image build process offers no benefit when its output is not connected to the HTML.

Frequently asked questions

Does Astro optimize images inside public/ automatically?

No. Astro serves files in public/ as static assets. Its built-in image features can optimize supported imported images, but CMS files kept in public/ need a separate processing strategy or image service if you want generated variants.

Is WebP always smaller than PNG?

Not in every situation. WebP is often more efficient for photographic or mixed-content images, but the result depends on image content, dimensions, quality settings, and the original format. Compare actual files and visible quality.

How many widths should I generate?

There is no single ideal number. Generate enough variants to cover your component widths and common device pixel ratios without creating unnecessary build artifacts. The eight widths used here reflect this site’s mix of logos, cards, and article images.

Not automatically. Apply it to the resource most likely to be your LCP bottleneck. On a text-focused homepage, the LCP element may be a headline rather than the logo.

Will 99/100 PageSpeed improve my Google rankings?

A high laboratory score is useful for diagnosing user experience, but it does not guarantee higher rankings. Focus on useful content, technical accessibility, and real-user Core Web Vitals as well as performance testing.

If you are building the same type of website, these guides cover the surrounding pieces:

Further reading


About the author: Duong Hoang Nam writes practical tutorials and engineering notes about modern web development, AI tools, and automation at DuongHoangNam.com.

About the Author

Duong Hoang Nam

Duong Hoang Nam

Software engineer sharing practical tutorials, real-world experiments, and insights on AI tools, automation, and web development.

Read My Story →

Related Articles