如何访问 DOM 以检测页面的Web字体何时加载?
我将29个ttf字体编码为单个CSS文件。页面上还有一个隐藏的 div,其中包含每个字体,以便浏览器将每个字体读入内存。该过程需要时间,因此我需要在浏览器将每个字体加载到内存后排队 AJAX 事件。
* 我知道 document.ready 和 window.onload 很接近,但我想在其他外部资源完成加载之前触发事件,以使 AJAX 更快地触发。
(请勿使用 jQuery)
================
示例代码:
HTML
<head>
...
<link type="text/css" rel="stylesheet" href="TTF-embedded-fonts.css" />
<script type="text/javascript" src="load-fonts.js"></script>
</head>
load-fonts.js
var ST1 = document.createElement('div');
ST1.setAttribute('id', 'fontloader');
ST1.innerHTML = "<span style='font-family:samplefont'>a<b>b<i>c</i></b><i>d</i></span> ... ";
ST1.style.cssText = "height:0px;text-indent:-9999px;visibility:hidden";
window.document.body.onload = appendST1 ();
function appendST1() { document.body.appendChild(ST1) };
[FONT-LOAD HANDLER HERE] { API.Ajax.loadComplete("load-fonts.js") };
TTF-embedded-fonts.css
@font-face {
font-family: 'samplefont';
src: url(data:font/truetype;charset=utf-8;base64,AAAE...) format('truetype');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'samplefont';
src: url(data:font/truetype;charset=utf-8;base64,AAAE...) format('truetype');
font-weight: bold;
font-style: normal;
}
@font-face {
font-family: 'samplefont';
src: url(data:font/truetype;charset=utf-8;base64,AAAE...) format('truetype');
font-weight: normal;
font-style: italic;
}
@font-face {
font-family: 'samplefont';
src: url(data:font/truetype;charset=utf-8;base64,AAAE...) format('truetype');
font-weight: bold;
font-style: italic;
}