2011-07-28 23 views
3

如何訪問DOM以檢測我的頁面的Web字體何時加載?如何檢測base-64編碼的網頁字體的「onload」?

我有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> 


負載-FO nts.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; 
} 
+0

舉例說明了你的意思? –

+1

@詹姆斯 - 我發佈了一份我正在使用的內容。 –

回答

0

Google's WebFont Loader解決了這個問題。使用custom module加載CSS,然後使用six javascript callback events中的任何一個來指示字體何時加載和/或加載失敗。

我測試過這種方法。它適用於base64編碼字體和常規鏈接字體。

*對於非javscript後備,請確保在使用Google WebFont加載器時在HTML中包含一個到CSS樣式表的重複鏈接。

0

要開始我就註釋掉ST1.style.cssText = "height:0px;text-indent:-9999px;visibility:hidden";線,以確保它是越來越寫入頁面正常。

假設有效的解決方案(雖然可能不是最好的)是<span>標籤後添加<script>標籤。

"<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);