StarYuhen - Caching
type: channel
link: https://www.yuhenm.top/tag/Caching/
items: Blog Optimization with Service Workers and Caching

Blog Optimization with Service Workers and Caching
type: item
date: 2023-11-06T22:43:38+08:00
description: IntroductionThe blog requires loading third-party fonts, which can be quite large, a whopping 16MB. As a result, I sought to optimize the on-demand loading of fonts and leverage Service Workers.On-Demand Font LoadingIn a typical CSS setup, fonts are automatically loaded, but every time the webpage is refreshed, they are downloaded again. To address this, I used JavaScript to create a binary blob file in the browser, caching the font. Here's the code:fetch('https://api.yuhenm.top/api/file/source?name=LXGWWenKaiGBScreen.woff', { cache: 'force-cache' // Force cache }) .then(response => response.blob()) .then(blob => { // Create a temporary URL for the font file const fontUrl = URL.createObjectURL(blob); // Create a tag const style = document.createElement('style'); // Set the tag's content style.textContent = ` @font-face { font-family: LXGWWenKaiGBScreen; font-size: 16px; font-style: normal; font-display: swap; src: url(${fontUrl}) format('woff'); } * { font-family: LXGWWenKaiGBScreen; } body { font-family: LXGWWenKaiGBScreen; } `; // Add the tag to document.head.appendChild(style); // Mark the font caching status as loaded localStorage.setItem('customFontLoaded', 'true'); });However, this was not sufficient. Although I had OneDrive as a traffic outlet, the font size was still too large. To address this, I implemented on-demand loading by splitting the font into different fragments using Node.js.import { fontSplit } from "@konghayao/cn-font-split"; fontSplit({ FontPath: "./fonts/LXGWWenKaiGBScreen.ttf", destFold: "./build", css: { fontFamily: "LXGWWenKaiGBScreen", // Not recommended; we already have a built-in parsing module }, targetType: "woff2", // ttf woff woff2; note that browser support for eot files is very low, so we do not support it chunkSize: 50 * 1024, // Split size testHTML: true, // Output an HTML report file reporter: true, // Output a JSON report });The code above splits the font, allowing CSS to load the font content on demand:@font-face { font-family…