Fixing Thai Font Size Jumps with Self-Hosted Fonts
Every font-display value chooses what to sacrifice while waiting for fonts. swap allows text to change mid-page; optional allows the entire page to go without the intended font. The way to avoid either sacrifice is to have the fonts arrive before the first paint, which is possible when the files share an origin with the page.
1-minute summary
- Symptom / problem
- font-display optional gives zero CLS, but text size jumps between a hard refresh and a link click
- Who should read
- Developers of Thai sites that use Google Fonts and watch CLS
- Fix in short
- Self-host the 14 woff2 files for the latin and thai subsets on the same origin and preload the 6 files above the fold
I was working through this site's PageSpeed scores when I found an item flagging layout shifts caused by font swapping. I fixed it by changing a single parameter, and the lab results looked good: CLS was 0, as intended. But afterward, users reported twice that the site's text size kept changing, sometimes large and sometimes small, which was worse than the original problem I had set out to fix.
This article covers what that parameter does to a page, why the symptoms are more obvious in Thai, and how I moved all the fonts to my own server. At the end, I include figures for two other changes made in the same round—images and security headers—along with the mobile score ceiling that the page's own code cannot fix.
Symptoms: one font on a hard refresh, another after clicking a link
This site uses three font families, assigned to three CSS variables. serif is Trirong, used for headings, the logo, and statistics; sans is IBM Plex Sans Thai, used for body text; and mono is Space Mono, used for labels and the ticker. Originally, all three loaded from Google Fonts through a single link line.
The symptoms users saw were easy to reproduce. Hard refresh any page, and the heading would appear in Georgia, the first fallback in the serif stack. But clicking a link to the next page changed the heading to Trirong. The apparent size changed, and the line breaks changed, so readers felt that the site was changing its text size for no reason.
There is no need to judge by eye to confirm which font an open page is actually using. In DevTools, select a heading, open the Computed tab, and scroll to the bottom. The Rendered Fonts section lists the fonts actually used to draw the characters, which do not necessarily match the first entry in the declared font-family. The page opened by a hard refresh and the page reached by clicking a link showed different names. That was the first piece of evidence that made me stop suspecting my own CSS.
The measurement tool loads a single page with an empty cache and stops there. It sees only the first half of the story: a page that uses the fallback throughout and has no shift at all. The actual symptom comes from the difference between two pages opened in sequence, which none of the metrics in the report captures.
The first, wrong attempt: changing display=swap to display=optional
The original setting was display=swap, which behaves straightforwardly: show text in the fallback immediately, then swap whenever the intended font arrives. Differences in character widths cause lines to wrap again and content below them to move, so the measurement tool counts this as CLS.
I changed it to display=optional because I had read that it causes no shift, which is true. But the reason it causes no shift is that it gives the browser a very short window to wait for the font, around 100 ms. If the font does not arrive in that window, the browser uses the fallback for the entire page without swapping again. The font file still finishes downloading and enters the cache, though, so the next page gets the intended font from the start.
So optional did not eliminate the problem. It moved the font change from the middle of a page to the transition between pages. The measurement tool could not see it, but readers could.
The reason this is more obvious on Thai sites than on English sites is that Thai fonts and Georgia differ considerably in x-height and character width. Fallbacks designed to closely match Latin characters do not work well for Thai text. The difference is therefore not just the shape of the characters, but their apparent size and the line breaks across the entire page.
Always the intended font, but with a shift
Every page ends up using the intended font, giving it a consistent appearance. The cost is a shift when the font arrives. The later it arrives, the more noticeable the shift.
No shift, but the font is uncertain
Each page stays completely still. The cost is that the font depends on whether the file is already cached. Two consecutive pages can look different.
Downloading 14 woff2 files to serve myself
If the fonts arrive before the first paint every time, the font-display value does not matter, because there is no waiting period that forces a choice. The only way I could control this was to put the files on the same origin as the page and preload them myself.
I wrote a short Python script to request CSS from the Google Fonts css2 endpoint and extract only what I needed. There are two traps. First, the User-Agent must be set to Chrome; otherwise, the server returns CSS pointing to ttf files instead of woff2. Second, the returned CSS separates @font-face blocks by subset, with a comment naming the subset above each block. I kept only latin and thai, discarding all latin-ext, vietnamese, and cyrillic blocks because this site has no content in those languages.
# tools/fetch_fonts.py -- ดึง woff2 เฉพาะ subset ที่ใช้ แล้วสร้าง fonts.css
import re, pathlib, urllib.request
UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/124.0 Safari/537.36') # ไม่ตั้ง = ได้ ttf
CSS_URL = ('https://fonts.googleapis.com/css2'
'?family=IBM+Plex+Sans+Thai:wght@400;500;600'
'&family=Trirong:wght@600;700;800'
'&family=Space+Mono:wght@400;700'
'&display=swap')
KEEP = {'latin', 'thai'}
SHORT = {'IBM Plex Sans Thai': 'ibmthai', 'Trirong': 'trirong', 'Space Mono': 'spacemono'}
FONT_DIR = pathlib.Path('public/fonts')
CSS_OUT = pathlib.Path('public/css/fonts.css')
def get(url):
req = urllib.request.Request(url, headers={'User-Agent': UA})
with urllib.request.urlopen(req, timeout=30) as r:
return r.read()
css = get(CSS_URL).decode('utf-8')
# แต่ละบล็อกมีรูป: /* thai */ @font-face { ... }
blocks = re.findall(r'/\*\s*([\w-]+)\s*\*/\s*@font-face\s*\{(.*?)\}', css, re.S)
FONT_DIR.mkdir(parents=True, exist_ok=True)
rules, total = ['/* self-hosted fonts: latin + thai */'], 0
for subset, body in blocks:
if subset not in KEEP:
continue
family = re.search(r"font-family:\s*'([^']+)'", body).group(1)
weight = re.search(r'font-weight:\s*(\d+)', body).group(1)
src = re.search(r'url\((https://[^)]+\.woff2)\)', body).group(1)
urange = re.search(r'unicode-range:\s*([^;]+);', body).group(1)
name = f'{SHORT[family]}-{weight}-{subset}.woff2'
data = get(src)
(FONT_DIR / name).write_bytes(data)
total += len(data)
rules.append(
"@font-face{font-family:'%s';font-style:normal;font-weight:%s;"
"font-display:swap;src:url('/fonts/%s') format('woff2');"
"unicode-range:%s;}" % (family, weight, name, urange))
CSS_OUT.write_text('\n'.join(rules) + '\n', encoding='utf-8')
print(f'[OK] {len(rules) - 1} ไฟล์ รวม {total / 1024:.0f} KB')
The result was 14 files totaling about 230 KB: three sans weights times two subsets for six files, three serif weights times two subsets for another six files, and two mono weights with only latin for another two files. The generated fonts.css contains one @font-face block per file, like this:
/* public/css/fonts.css (ตัดมาสองบล็อก) */
@font-face{font-family:'Trirong';font-style:normal;font-weight:700;
font-display:swap;src:url('/fonts/trirong-700-thai.woff2') format('woff2');
unicode-range:U+02D7, U+0303, U+0331, U+0E01-0E5B, U+200C-200D, U+25CC;}
@font-face{font-family:'Trirong';font-style:normal;font-weight:700;
font-display:swap;src:url('/fonts/trirong-700-latin.woff2') format('woff2');
unicode-range:U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+2000-206F;}
I deliberately preserved two things from the original. The first was unicode-range, because it makes the browser load the thai file only when a page contains Thai characters, and the latin file only when it contains Latin characters, without combining them into a single large file. The second was the family names, because the site's main CSS already references the fonts through variables. Keeping the names meant I did not have to change a single line of the main CSS, only where the files came from.
For font-display, I went back to swap. With preload in place, the fonts arrive before there is anything to swap, so swap is just a safety net for weights that are not preloaded.
Preloading 6 files used above the fold, and the crossorigin you must not forget
I did not preload all 14 files, because every preload competes with CSS and the page's first image. I selected only the weights actually used above the fold, which came to six files.
| File | Used for above the fold |
|---|---|
| sans 400 thai + latin | Body text |
| serif 700 thai + latin | Headings |
| serif 800 latin | Logo and statistics |
| mono 400 latin | Labels and ticker |
<link rel="preload" as="font" type="font/woff2" href="/fonts/ibmthai-400-thai.woff2" crossorigin>
<link rel="preload" as="font" type="font/woff2" href="/fonts/ibmthai-400-latin.woff2" crossorigin>
<link rel="preload" as="font" type="font/woff2" href="/fonts/trirong-700-thai.woff2" crossorigin>
<link rel="preload" as="font" type="font/woff2" href="/fonts/trirong-700-latin.woff2" crossorigin>
<link rel="preload" as="font" type="font/woff2" href="/fonts/trirong-800-latin.woff2" crossorigin>
<link rel="preload" as="font" type="font/woff2" href="/fonts/spacemono-400-latin.woff2" crossorigin>
<link rel="stylesheet" href="/css/fonts.css">
Fonts are always requested using anonymous CORS, wherever they are hosted. If the preload lacks the crossorigin attribute, the browser treats it as a different kind of request from the actual @font-face request. The result is that the same file downloads twice: the first download is wasted, and the one actually used arrives just as late as before. Check the Network tab: each woff2 filename should appear only once.
Then I removed the Google Fonts link and all preconnect entries from the layout. The site no longer depends on an external origin for fonts. I tested three times with an empty cache and network throttling. The intended fonts appeared every time, CLS was 0, and text size did not jump on either the first load or the next page.
- Run the font download script. Check that the files are woff2, not ttf, and that the file count matches the intended weights times subsets.
- Add
fonts.cssand preload only the weights used above the fold, withcrossoriginon every line. - Remove all link and preconnect entries for the old font provider. Do not leave both loading methods in place.
- Open the Network tab and filter for font. There should be no requests to other domains and no duplicate files.
- Test several times with an empty cache and throttling, then click through to another page. The fonts must be the same on both pages.
A deployment trap: static files must exist in both locations
This site is deployed with the web server's docroot separate from the application folder. Static files therefore need to exist both in the docroot that actually serves them and in the application's public directory, which the helper uses for references. Forget either side, and woff2 requests return 404, silently sending everything back to fallback fonts, which looks exactly like the symptom I just fixed. This command checks it after transferring the files.
for f in ibmthai-400-thai trirong-700-thai trirong-800-latin spacemono-400-latin; do
curl -s -o /dev/null -w "%{http_code} %{content_type} $f\n" \
"https://example.com/fonts/$f.woff2"
done
# ต้องได้ 200 font/woff2 ทุกบรรทัด
Related work: WebP images and security headers
In the same round, I fixed two other issues flagged in the report. The first was images. The 1200x630 landscape cover image was originally a PNG of about 200 KB. Converting it to WebP at quality 80 with Pillow brought it down to 14 KB. The square sidebar image was originally 250 KB; I resized it to 240 px, bringing it down to 2.3 KB.
from PIL import Image
def to_webp(src, dst, width=None, quality=80):
im = Image.open(src).convert('RGB')
if width and im.width > width:
im = im.resize((width, round(im.height * width / im.width)), Image.LANCZOS)
im.save(dst, 'WEBP', quality=quality, method=6)
to_webp('cover.png', 'cover.webp') # 1200x630 ประมาณ 200 KB -> 14 KB
to_webp('square.png', 'square.webp', width=240) # sidebar 250 KB -> 2.3 KB
There was one exception: og:image still points to the original PNG because some scrapers do not support WebP. I added fetchpriority="high" to the page's first image and loading="lazy" decoding="async" to the rest. Overall, the home page went from 4.1 MB to about 1 MB, and images above the fold went from 2.5 MB to 18 KB.
The second issue was four security headers, added through a single middleware.
<?php
// app/Http/Middleware/SecurityHeaders.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class SecurityHeaders
{
public function handle(Request $request, Closure $next)
{
$response = $next($request);
$response->headers->set('X-Content-Type-Options', 'nosniff');
$response->headers->set('X-Frame-Options', 'SAMEORIGIN');
$response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
$response->headers->set('Strict-Transport-Security', 'max-age=2592000'); // 30 วัน
return $response;
}
}
These four lines raised the Best Practices score from 81 to 100.
Scores after the fixes, and the mobile ceiling the page's code cannot fix
Desktop finished at 98, but mobile rose from 54 and stalled at 67, with FCP still at 4.3 seconds and LCP at 6.1 seconds, despite the much smaller fonts and images. I went through the CPU timing entries in the report and found that three advertising scripts were consuming time on the throttled mobile CPU: the consent script at 5,841 ms, the ad renderer at 4,136 ms, and the loader at 2,423 ms, while the page's own critical path took 376 ms.
Desktop reached 98 because its CPU was fast enough to handle the work from those scripts. The mobile lab test simulates a slow CPU, so the same work takes several seconds. Only one lever remains: defer loading the advertising scripts until the user starts interacting. That is a direct tradeoff between scores and revenue, because ads that load later are ads that fewer people see. I have not done this myself, and I do not think there is a universal answer; the choice depends on each site's priorities.
The public PageSpeed API starts returning 429 very quickly when called repeatedly. If you need several before-and-after measurements in one day, run them directly on the tool's website instead of calling the API.
If I had to reduce this to one point, it would be: do not fix font problems by changing font-display alone. That value only chooses how users experience fonts that are not ready. The actual fix is to have the fonts ready before the first paint, and Thai sites benefit more from this than sites in other languages because our fallbacks differ more from the intended fonts. The font download script above can be used on other sites simply by changing the family names and weights. If I have left anything out or made a typo, I will come back and correct it later.
Want us to set this up?
Get help with server setup, configuration, migration, or troubleshooting. Save time for the work that matters.
Hit something like this? Stuck somewhere?
Come trade notes on the LinuxThai board



Comments 0
No comments yet — be the first