Home > Web Front-end > CSS Tutorial > How Can I Detect When a Custom Font Loaded Using @font-face?

How Can I Detect When a Custom Font Loaded Using @font-face?

Susan Sarandon
Release: 2024-12-27 22:31:09
Original
437 people have browsed it

How Can I Detect When a Custom Font Loaded Using @font-face?

How to Detect the Loading of a Custom Font (@font-face)?

When incorporating custom fonts using the @font-face rule, it's essential to determine when the font files have successfully loaded. Without this knowledge, you may encounter the issue of placeholder characters (e.g., "") displaying until the fonts are available.

Solution: jQuery FontSpy.js

A popular solution is the jQuery FontSpy.js plugin, which allows you to style elements based on whether the custom font has loaded.

Implementation

To utilize FontSpy.js, follow these steps:


  1. Include the plugin's JavaScript file in your project.

  2. Apply the fontSpy function to the elements that will display the custom font.

  3. Configure options such as the onLoad and onFail classes to apply when the font is loaded or fails to load, respectively.

The plugin works by comparing the width of a string displayed in two different fonts. When the widths differ, it indicates that the custom font has loaded successfully.

Code Example

Consider the following snippet, which applies FontSpy.js to an element with the class my-icons:

<br>$(document).ready(function() {<br>  $('.my-icons').fontSpy({</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">onLoad: 'show-icons',
onFail: 'hide-icons'
Copy after login

});
});

Once the custom font loads, the show-icons class will be applied to the element, making the icons visible. If the font fails to load, the hide-icons class will be applied instead.

Additional Considerations

  • Fallback Font: Specify a fallback font in the fontSpy configuration to display in case the custom font fails to load.
  • Timeout: FontSpy.js includes a timeout mechanism to prevent infinite waiting. Configure the timeOut option to avoid potential delays.
  • Browser Support: FontSpy.js supports modern browsers, including Chrome, Firefox, Safari, and Edge.
  • Cross-Origin Fonts: FontSpy.js handles cross-origin font loading seamlessly.

The above is the detailed content of How Can I Detect When a Custom Font Loaded Using @font-face?. 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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template