❌

Normal view

There are new articles available, click to refresh the page.
Today β€” 2 December 2026Emile Choghi

Manually Subset Fonts to Save Bandwidth

9 May 2025 at 00:00

When I started building Cat Cafe Map, I really wanted to keep things as minimal and fast as possible. No unnecessary frameworks, no giant libraries, just a clean site that loads quickly and feels light.

Most of the pages are statically rendered, and I barely touch JavaScript thanks to Astro Islands. My first version shipped under 10kb of JavaScript per page, which felt great. But there was one thing bugging me: my font file. The woff2 file came in at 33kb, which made it three times bigger than the JS payload. Not the end of the world, but it definitely felt unnecessary.

So I decided to trim it down. I added a little build step to subset the font so it only included the glyphs I actually use across the site. To do that, I hacked together a Bash script that scanned through the dist folder, collected all the characters used, and passed them into fonttools to generate a slimmer font file.

The difference was pretty satisfying. The font went from 33kb down to about 10kb, which is roughly a 70% reduction. It doesn’t make a huge difference, but it’s a small optimization that makes the site snappier and keeps bandwidth usage lower.

A terminal showing the file-size savings from font subsetting

Here’s a simple example of how I did it using Bash, Python, and fonttools:

process-fonts.sh
#!/bin/bash
 
# Check and install dependencies
check_and_install_dependencies() {
    # Check for pip
    if ! command -v pip &> /dev/null; then
        echo "pip is not installed. Please install Python and pip first."
        exit 1
    fi
 
    # Check for fonttools and brotli
    if ! python3 -c "import fontTools" &> /dev/null || ! python3 -c "import brotli" &> /dev/null; then
        echo "Installing required Python packages..."
        pip install fonttools brotli
    fi
}
 
# Directory containing your build files
BUILD_DIR="./dist" # adjust this to your build directory
# Directory containing your fonts
FONTS_DIR="./public/fonts"
# Output directory for subsetted fonts
SUBSET_DIR="./public/fonts"
 
# Create subset directory if it doesn't exist
mkdir -p "$SUBSET_DIR"
 
# Function to extract text content from files
extract_text() {
    # Extract text from HTML, JS, CSS files
    find "$BUILD_DIR" -type f \( -name "*.html" -o -name "*.js" -o -name "*.css" \) -exec cat {} + | \
    # Remove HTML tags
    sed 's/<[^>]*>//g' | \
    # Remove special characters but keep unicode
    tr -cd '[:alnum:][:space:][:punct:]\\u0080-\\uffff' | \
    sort -u > /tmp/text_content.txt
}
 
# Create subsets for each font
create_subset() {
    local font=$1
    local basename=$(basename "$font")
    local output="$SUBSET_DIR/${basename%.*}.subset.${basename##*.}"
 
    echo "Creating subset for $basename..."
 
    pyftsubset "$font" \
        --output-file="$output" \
        --text-file=/tmp/text_content.txt \
        --layout-features='*' \
        --flavor=woff2 \
        --desubroutinize
 
    echo "Created subset font: $output"
 
    # Print size comparison
    original_size=$(stat -f %z "$font")
    subset_size=$(stat -f %z "$output")
    echo "Original size: $(($original_size/1024))KB"
    echo "Subset size: $(($subset_size/1024))KB"
    echo "Reduction: $((100-($subset_size*100/$original_size)))%"
}
 
echo "Checking dependencies..."
check_and_install_dependencies
 
echo "Cleaning up old subset fonts..."
find "$SUBSET_DIR" -type f -name "*subset*" -delete
 
echo "Extracting text content from build..."
extract_text
 
echo "Creating font subsets..."
for font in "$FONTS_DIR"/*.woff2; do
    create_subset "$font"
done
 
echo "Cleanup..."
rm /tmp/text_content.txt
 
echo "Done! Subsetted fonts are in $SUBSET_DIR"
Creating font subsets via fonttools

The Correct Way to Load Google AdSense in Next.js

2 April 2025 at 00:00

Adding Google Adsense to a Next.js site is fairly straightforward and simple. You can install @ctrl/react-adsense, use the component with your credentials, and add the Adsense script to pages/_app.js if you’re using Page Router or app/layout.tsx for App Router.

At first glance, this might seem like all you need, but I found out the hard way that this basic implementation is not enough to get the job done. Read on if you’re interested why, otherwise skip to the solution.

A Next.js implementation of Google AdSense

pages/_app.tsx
import Script from 'next/script'
 
// This part was ok βœ…
export default function App({ Component, pageProps }) {
  return (
    <>
      <Script
        strategy="afterInteractive"
        src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXX"
        crossOrigin="anonymous"
      />
      <Component {...pageProps} />
    </>
  )
}
Loading the script in Next with page router
AdBanner.tsx
import React from 'react'
import { Adsense } from '@ctrl/react-adsense'
 
// This part was not ❌
export function AdBanner() {
  return <Adsense client="ca-pub-XXXXXXXXXXXXXXXX" slot="XXXXXXXXXX" />
}
Minimal react-adsense setup

The Problem

After running this setup for about four months on a site averaging around 30,000 pageviews per month, I started noticing something odd. My daily ad revenue seemed unusually low, but I initially chalked it up to typical Adsense RPMs. It’s well-known that Adsense doesn’t pay as well as some other ad networks, but given their low barrier to entry, I accepted it as part of the tradeoff.

What didn’t add up was that my analytics dashboard was showing more than twice the pageviews reported by Google Adsense. It didn’t take long to realize that the root cause was likely related to how Next.js handles routing and rendering.

Next.js is a single-page application (SPA) framework under the hood, even when using traditional routing patterns. This means that when users navigate between pages, the browser doesn’t fully reload the page, it simply swaps out content dynamically. While this is great for performance and user experience, it introduces a subtle problem: scripts like Google AdSense are designed to detect full page loads, not internal client-side navigations. As a result, while users were technically viewing multiple pages per session, AdSense wasn’t registering those views because it only initialized once on mount. Without a proper fix, every client-side page change was effectively invisible to the ad system.

The site I was working on, GigFish, is a directory where users typically spend 5 minutes or more per session, browsing an average of 5 or more pages. Because my AdBanner component was only rendering once on a route like the discover page, I was missing out on several page views per user session.

On subsequent navigations, the ad banner kept displaying the same ad because the component never re-rendered.

The Solution

To fix the issue, I replaced the @ctrl/react-adsense component with my own implementation. It’s almost identical but adds a key based on the router path and a retry mechanism to ensure the ad banner is filled if the initial load fails.

Adsense.tsx
import React from 'react'
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import { cn } from '@/lib/utils'
 
export function Adsense({
  className = '',
  style = { display: 'block' },
  client,
  slot,
  layout = '',
  layoutKey = '',
  format = 'auto',
  responsive = 'false',
  pageLevelAds = false,
  adTest,
  children,
  ...rest
}) {
  const router = useRouter()
 
  useEffect(() => {
    const p = {}
    if (pageLevelAds) {
      p.google_ad_client = client
      p.enable_page_level_ads = true
    }
 
    // Fill the space with an ad
    const doPush = () => {
      if (typeof window !== 'object') return
      window.adsbygoogle = window.adsbygoogle || []
      window.adsbygoogle.push(p)
    }
 
    const pushAds = () => {
      try {
        doPush()
      } catch {
        // πŸ‘‡ THIS IS A FAILSAFE
        setTimeout(() => {
          try {
            doPush()
          } catch (err) {
            console.error('AdSense push retry failed:', err)
          }
        }, 750)
      }
    }
 
    pushAds()
  }, [router.asPath, client, slot, pageLevelAds])
 
  return (
    <ins
      key={router.asPath} // πŸ‘ˆ THIS IS THE IMPORTANT FIX
      className={cn('adsbygoogle', className)}
      style={style}
      data-ad-client={client}
      data-ad-slot={slot}
      data-ad-layout={layout}
      data-ad-layout-key={layoutKey}
      data-ad-format={format}
      data-full-width-responsive={responsive}
      data-adtest={adTest}
      {...rest}
    >
      {children}
    </ins>
  )
}
Filling new ads when the route changes

The router.asPath key signals to React that the component has changed and needs to be re-rendered. Inside the effect, logic attempts to populate the banner with a new ad. If the first attempt fails, which can happen due to the asynchronous loading of the Adsense script, it retries after 750ms. If, after all this, the ad still has the data-ad-status="unfilled" attribute, it’s likely because the Google Adsense script chose not to serve an ad.

After making this change, my AdBanner component correctly re-rendered whenever the URL’s query parameters changed, and I started seeing different ads when navigating between pages. As a result, the pageview count in my Adsense reports began to align much more closely with the numbers from my analytics dashboard. While it’s still a bit early to be certain, my daily ad revenue now looks likely to double in the coming months. πŸ₯³

How to Add a Noise Effect with CSS

20 March 2025 at 00:00

Scrolling through X (Twitter) the other day, I came across a designer showing some landing page concepts he had made with Figma. They all featured this aesthetically pleasing, grainy effect that softened the sharpness of the images.

The basic concept was that he had prompted his way to creating these clean, high-definition image outputs from Midjourney, applied headings, buttons, and marketing copy, then finished it off with this β€œnoise” effect. The result was an accessible approach to quickly designing landing page ideas that got him a few leads to his business without having to even create the actual site.

Noise Effect Tweet

Unfortunately, for design illiterate devs like me, the process involved a Figma plugin called β€œShumi Noise”, but it seemed like an easy CSS solution must exist. If you’re interested in the original twitter thread, you can find it here.

Below is a simple proof of concept for an overlay that applies the effect to an image or any element the class is applied to. Simply adjust the opacity or base frequency to produce the desired level of graininess. baseFrequency controls how tight or loose the noise pattern feels, numOctaves adds extra layers of texture, and the opacity on the SVG rectangle keeps the effect from overpowering the actual design. Coupled with some crisp photography, AI artwork, or other design, the effect can make for some pretty epic landing pages with little effort.

Base image
Base Frequency: 0.75
Opacity: 0.30

For a live page, I prefer keeping the grain as a CSS overlay so it can be adjusted without permanently changing the image. For static assets like the cover image or social preview card, baking in a heavier grain pass is totally reasonable since those surfaces won’t run the interactive CSS.

noise-overlay.css
.noise {
  position: relative;
  overflow: hidden;
}
 
.noise::before {
  content: '';
  position: absolute;
  inset: 0;
  z-index: 1;
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%25' height='100%25'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.75' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.3'/%3E%3C/svg%3E");
  pointer-events: none;
}
Add this class to an element to apply noise

The important bit is that .noise needs to be positioned relative, otherwise the absolutely positioned ::before pseudo-element may try to cover some other ancestor instead of the element you meant to target. The content property is what makes the pseudo-element render, and pointer-events: none keeps the overlay from blocking buttons, links, or other interactive pieces underneath it.

For example, you could apply it to a hero like this:

index.html
<section class="hero noise">
  <h1>Your landing page headline</h1>
  <p>Some crisp copy over a crisp image.</p>
</section>

The effect generally looks best when applied to an entire hero section rather than just an image, and most designers pair it with a gradient effect to taper off the graininess towards the edges of the page. It’s a clean way to soften up the bold colors and visual sharpness you usually get from AI image outputs in tools like Midjourney.

Code is Leverage

30 December 2024 at 00:00

What first drew me to programming was the novelty of creating something out of nothing. The idea that I could write a few lines of code and have it turn into a website as simply as you would stack legos as a kid. It felt like play.

But as I grew into my profession, I realized that the code is not the hard part. The hard part is deciding what to build, how to sell it, and who to market it to. The difficult part is building the business, not the programming.

To stay employed solely as a programmer, taking a salary dictated by office politics, an arbitrary title, or location is to trade your potential for a small slice of certainty. It’s a promise of safety without the possibility of non-linear outcomes β€” work that ends when you stop working.

The real gift of software is leverage. Code is a modern daemon, quietly compounding your effort without fatigue or complaint. It scales beyond your time and energy. You can build it once, and it can serve millions while you sleep. That’s where the real power of programming lies.

Software turning one person’s effort into leverage

The problem with a traditional job is simple: it doesn’t scale. Your income is limited to the time you have available. Your hours become your ceiling. Without ownership, without equity, you are simply renting out your most limited resource.

Worse still, you could code features at work that generate millions, but the spoils aren’t yours. The incentive is to do just enough to meet expectations, but not to exceed them. Why give your best when the upside belongs to someone else?

The real shift happens when you realize that leverage is no longer reserved for the elite. In the past, you needed capital, connections, or factories. Today, you only need a laptop and an internet connection. Code is permissionless leverage. No one needs to give you authority. You can simply build.

The toughest obstacle isn’t learning to code, it’s having the courage to use it for yourself. Most will choose the familiar path: salaries, titles, healthcare, β€œunlimited” PTO, and praise from bosses who own the real upside. But the few who step off that path and build for themselves unlock the possibility of asymmetric upside. They stop renting out time and start building equity in something that’s entirely theirs.

If you can code, you already hold the keys. The ability to create, automate, and scale is sitting in your hands. No one is stopping you. The only thing left is to act: to place the bet, to take the risk, to build something of your own.

Bet on yourself.

❌
❌