Home > Web Front-end > CSS Tutorial > How Can We Detect When CSS `@font-face` Fonts Have Loaded to Prevent Broken Icon Display?

How Can We Detect When CSS `@font-face` Fonts Have Loaded to Prevent Broken Icon Display?

Barbara Streisand
Release: 2024-12-29 03:38:11
Original
741 people have browsed it

How Can We Detect When CSS `@font-face` Fonts Have Loaded to Prevent Broken Icon Display?

Detecting Font Loading Status for CSS @font-face

Issue:
When integrating a font using @font-face, icons may initially appear as unstyled circles with ⓘ symbols instead of their intended design. This issue arises because the font files take time to load.

Query:
How can we determine if the @font-face font files have been loaded to ensure proper icon display?

Answer:

jQuery-FontSpy.js Plugin:

This open-source plugin detects font loading status by comparing the width of a string rendered in Comic Sans MS (a widely available font) with the same string rendered in the custom font you wish to load. When the widths differ, the custom font has been successfully loaded.

Customization:

  • onLoad: Class added when the font is loaded.
  • onFail: Class added if the font fails to load.
  • testFont: A widely available font like "Comic Sans MS".
  • testString: A distinctive string used for width comparison.
  • delay: Time between font width checks.
  • timeOut: Maximum time to wait before assuming font failure.

Usage:

  1. Include the jQuery-FontSpy.js plugin in your HTML.
  2. Apply the .bannerTextChecked class to elements whose font loading you wish to detect.
  3. Initialize the plugin:
$('.bannerTextChecked').fontSpy({
  onLoad: 'hideMe',
  onFail: 'fontFail anotherClass'
});
Copy after login
  1. Define custom CSS classes to control element visibility based on font loading status.

Example:

.hideMe {
  visibility: hidden !important;
}

.fontFail {
  visibility: visible !important;
  /* Style to resemble the custom font */
}
Copy after login

Additional Notes:

  • FontAwesome compatibility is currently not supported.
  • For further details and a live demo, visit: https://patrickmarabeas.github.io/jQuery-FontSpy.js

The above is the detailed content of How Can We Detect When CSS `@font-face` Fonts Have Loaded to Prevent Broken Icon Display?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template