我目前正在使用jQuery构建一个动画布局,并且我正在使用.width()找出div的宽度。但是,有时它会在TypeKit被激活之前获取.width() (因此给出了错误的宽度)。
有没有办法通过使用if statement来检查TypeKit何时加载
发布于 2014-02-13 23:19:11
是的,有。
您可以使用带回调的Typekit.load (docs),而不是在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);
}https://stackoverflow.com/questions/21757556
复制相似问题