首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查Typekit是否已加载JavaScript

检查Typekit是否已加载JavaScript
EN

Stack Overflow用户
提问于 2014-02-13 22:52:40
回答 1查看 1.6K关注 0票数 1

我目前正在使用jQuery构建一个动画布局,并且我正在使用.width()找出div的宽度。但是,有时它会在TypeKit被激活之前获取.width() (因此给出了错误的宽度)。

有没有办法通过使用if statement来检查TypeKit何时加载

EN

回答 1

Stack Overflow用户

发布于 2014-02-13 23:19:11

是的,有。

您可以使用带回调的Typekit.load (docs),而不是在head标记中调用常用的try{Typekit.load();}catch(e){}

代码语言:javascript
复制
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) {}

我只是为我自己的项目做了这件事,我没有能力改变代码。因此,如果你处于同样的情况,试试这个:

代码语言:javascript
复制
// 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);
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21757556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档