国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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

Improving Font Performance with Subsetting and Local Storage

Feb 20, 2025 pm 12:09 PM

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';

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;
  }
};

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();
  };
}

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();
}

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';
}

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;
}

(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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

What's the Difference Between Java and JavaScript? What's the Difference Between Java and JavaScript? Jun 17, 2025 am 09:17 AM

Java and JavaScript are different programming languages. 1.Java is a statically typed and compiled language, suitable for enterprise applications and large systems. 2. JavaScript is a dynamic type and interpreted language, mainly used for web interaction and front-end development.

See all articles