【发布时间】:2014-02-13 14:52:39
【问题描述】:
我目前正在构建一个使用 jQuery 制作动画的布局,并且我正在使用 .width() 找出 div 的宽度。但是,有时它会在激活 TypeKit 之前获得.width()(因此给出了不正确的宽度)。
有没有办法使用if statement 来检查 TypeKit 何时加载?
【问题讨论】:
标签: javascript jquery typekit
我目前正在构建一个使用 jQuery 制作动画的布局,并且我正在使用 .width() 找出 div 的宽度。但是,有时它会在激活 TypeKit 之前获得.width()(因此给出了不正确的宽度)。
有没有办法使用if statement 来检查 TypeKit 何时加载?
【问题讨论】:
标签: javascript jquery typekit
是的,有。
您可以使用带有回调 (docs) 的 Typekit.load,而不是在 head 标记中调用通常的 try{Typekit.load();}catch(e){}:
try {
Typekit.load({
loading: function() {
// JavaScript to execute when fonts start loading
},
active: function() {
// JavaScript to execute when fonts become active
// this is where you want to init your animation stuff
},
inactive: function() {
// JavaScript to execute when fonts become inactive
}
})
} catch(e) {}
我只是为我自己的项目完成了这项工作,我没有能力更改该代码。所以如果你遇到同样的情况,试试这个:
// configure these
var check_interval = 100; // how many ms to leave before checking again
var give_up_after_ms = 2000; // how many ms before we consider the page loaded anyway.
// caches etc
var count = 0;
var count_limit = give_up_after_ms / check_interval;
var html = $("html");
var font_loaded_check_interval;
var check_load_status = function(callback) {
if(html.hasClass("wf-active") || count >= count_limit) {
// fonts are loaded or give_up_after_ms was reached
if(font_loaded_check_interval) {
clearInterval(font_loaded_check_interval);
font_loaded_check_interval = null;
}
// call the callback
callback.call(this);
return true;
}
count++;
return false;
};
function doneCallback() {
// code to run when fonts are loaded or timeout reached
alert("Done");
}
// check on initial run of JS, and if not ready, start checking at regular intervals.
if( ! check_load_status(doneCallback)) {
font_loaded_check_interval = setInterval(function() {
check_load_status(doneCallback);
}, check_interval);
}
【讨论】: