Home > Web Front-end > JS Tutorial > Improving Font Performance with Subsetting and Local Storage

Improving Font Performance with Subsetting and Local Storage

尊渡假赌尊渡假赌尊渡假赌
Release: 2025-02-20 12:09:09
Original
593 people have browsed it

Improving Font Performance with Subsetting and Local Storage

Key Points

  • Font subsetting: Remove unused characters in web fonts, significantly reduce file size, and improve web font performance. Tools such as Font Squirrel's webfont generator assist in the subsetting and encoding process.
  • Rollback Font: Display the fallback system font during the actual font download, ensuring instant access to the website content and improving the perceived performance of the website or application.
  • Local Storage: Save web fonts in local storage to significantly improve font performance. Fonts can persist after a session or even device restart without having to re-download each time the webpage is loaded. However, it should be noted that this method depends on whether the user's browser supports local storage.

A recent technology that has attracted much attention is to use a subsetting method to reduce the size of web page fonts, encode it as base64, and store it in local storage. If used improperly, web fonts can seriously affect performance and may prevent access to website content.

This technique reduces the size of the font file and stores it asynchronously in local storage, displaying fallback system fonts during font downloads. This is combined with some inherent features of local storage to enable fonts to be cached persistently. This means that the font will remain on the client machine and will remain across sessions and even after device restart.

Font subset

Font subsetting is one of the most important ways to improve the performance of web fonts. Subsetting is to delete unused characters from font files. Unused characters are usually characters in languages ​​you do not use, or special characters that your website or application may not require but are usually embedded in font files. With subsetting, you can reduce file size by up to 50%.

You can use Font Squirrel's webfont generator to subset and base64 encoding to generate a final file (make sure to select the expert option to access custom subsetting and select " in the "CSS" section of the form Base64 encoding”).

When finished, you will get a stylesheet file with all compressed web fonts that can be reused with a single request.

Select a fallback font

To avoid users waiting while the browser tries to download the font file, it is best to display the fallback system font. This allows immediate access to content (after all, that's what users visit the website for).

Loading fonts simultaneously will keep the text blank while the browser waits for the font file, and users will not be able to read the content while waiting for the file to be downloaded.

Using asynchronous loading and appropriate fallback fonts, the user will immediately see the text displayed in fallback fonts and switch to the web font of your choice after the file download is complete.

You can style the fallback fonts to smoother transitions and reduce content rearrangement. This immediately improves the perceived performance of your website or app because users can access your content without delay.

To find system fonts available for different operating systems, you can view the following resources:

  • CSS Font Stack – A complete collection of web-secured CSS Font Stacks for Mac and Windows.
  • iOS Fonts – Lists each font for each iOS version.

On Android, it is difficult to determine which system fonts are due to the presence of a large number of branches and different brands. However, the most common fonts on Android are: Droid Serif, Droid Sans, Droid Mono, and Roboto.

Save web fonts using local storage

First, we add a class to the DOM node that will save the fallback font style. Later, we will use JavaScript to replace it with a class with a loaded font style. We will also save the path to the font file to a variable for reuse later.

document.documentElement.className = 'fallback';
var css_href = '../path/fonts.css';
Copy after login

Next, we need to check local storage support by trying to set up the project to local storage and get the project from it. Some browsers cannot store anything in private mode, but window.localStorage will still return the storage object. We need this extra request to make sure our script works:

var localStorageSupported = function() {
  try {
    localStorage.setItem('test', 'test');
    localStorage.removeItem('test');
    return true;
  } catch(e) {
    return false;
  }
};
Copy after login

If the browser passes the localStorageSupported test and our font file is stored, we can get the file and add it to the style tag inside the page title using the injectRawStyle() function. If the browser fails the test, call the injectFontsStylesheet() function on the onLoad event so that the ui thread will not be blocked:

if (localStorageSupported() && localStorage.webFonts) {
  injectRawStyle(localStorage.webFonts);
} else {
  window.onload = function() {
    injectFontsStylesheet();
  };
}
Copy after login

injectFontsStylesheet() function issues an xhr request to get the font file contents, inject it into the title with the injectRawStyle function and save it to local storage:

function injectFontsStylesheet() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', css_href, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      injectRawStyle(xhr.responseText);
      localStorage.webFonts = xhr.responseText;
    }
  };
  xhr.send();
}
Copy after login

This function creates a style tag at the head of the document and gets its contents through the text parameter. At this stage, we also replace the fallback class with a font class with a web font style:

function injectRawStyle(text) {
  var style = document.createElement('style');
  style.innerHTML = text;
  document.getElementsByTagName('head')[0].appendChild(style);
  document.documentElement.className = 'webFont';
}
Copy after login

Now we need to fall back on the actual styles of fonts and web fonts. You can test these styles by refreshing your browser and observing the rearrangement of your content. The goal is to match the fallback font styles as much as possible to make the actual style so that the perception of change becomes nearly imperceptible.

.fallback {
  font-family: Verdana, sans-serif;
  line-height: 1.58em;
  letter-spacing: 0px;
  font-size: 9px;
}

.webFont {
  font-family: 'Proxima-Nova', sans-serif;
  line-height: 1.3em;
  letter-spacing: 2px;
  font-size: 13px;
}
Copy after login

(The demonstration and summary part is too long, and it is recommended to selectively retain or streamline according to actual conditions) This part mainly contains CodePen demonstration links and a summary of the previous content, which can be adjusted as needed. The key is to retain core technical points, such as subsetting, fallback fonts and local storage usage methods. The FAQ section can also be streamlined or retained as needed.

The above is the detailed content of Improving Font Performance with Subsetting and Local Storage. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template