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:
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'
});
});
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
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!