检查Typekit是否已加载JavaScript

时间:2014-02-13 14:52:40

标签: javascript jquery typekit

我正在构建一个使用jQuery动画的布局,我正在使用.width()找到div的宽度。但是,有时它会在TypeKit被激活之前得到.width()(从而给出不正确的宽度)。

有没有办法通过使用if statement

来检查何时加载了TypeKit

1 个答案:

答案 0 :(得分:3)

是的,有。

您可以将Typekit.load与回调(docs)一起使用,而不是调用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);
}
相关问题