如何检测base-64编码的webfonts的“onload”?

时间:2011-07-28 23:26:23

标签: javascript ajax dom onload

如何访问DOM以检测我的网页的webfonts何时加载?

我将29个.ttf字体base64编码到一个CSS文件中。我在页面上还有一个使用每种字体的隐藏div,以使浏览器将每种字体读入内存。这个过程需要时间,所以我需要在浏览器将每个字体加载到内存后将AJAX事件排队。

*我知道document.readywindow.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>


负载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-嵌入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;
}

2 个答案:

答案 0 :(得分:0)

首先,我会注释掉ST1.style.cssText = "height:0px;text-indent:-9999px;visibility:hidden";行,以确保它正确地写入页面。

假设一个解决方案(尽管可能不是最好的)是在<script>标记之后添加<span>标记。

"<span style='font-family:samplefont'>1a<b>b<i>c</i></b><i>d</i></span>"
+ "<scrip" + "t type=\"text/javascr" + "ipt\">\n" 
+ "Code Goes here" 
+ "\n</scri" + "pt>"

如果有的话,我会通过jQuery添加它:

var ST1 = $("<div><span style='font-family:samplefont'>1a<b>b<i>c</i></b><i>d</i></span><scrip" 
+ "t type=\"text/javascr" + "ipt\">\n" 
+ "Code Goes here" 
+ "\n</scri" + "pt></div>");
$(document.body).append(ST1);

答案 1 :(得分:0)

Google's WebFont Loader解决了这个问题。使用custom module加载CSS,然后使用任何six javascript callback events来表示字体加载和/或加载失败。

我测试过这种方法。它适用于base64编码字体和定期链接的字体。

*对于非javscript后备,请确保在使用Google WebFont Loader时在HTML中包含指向CSS样式表的重复链接。