我目前正在构建一个使用jQuery进行动画处理的布局,并且正在使用.width()
找出div的宽度。但是,有时在激活TypeKit之前会得到.width()
(因此给出了错误的宽度)。
有没有一种方法可以使用if statement
检查TypeKit是否已加载?
最佳答案
就在这里。
可以在回调(docs)中使用Typekit.load,而不用在try{Typekit.load();}catch(e){}
标记中调用通常的head
:
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);
}
关于javascript - 检查Typekit是否已加载JavaScript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21757556/