gpt4 book ai didi

javascript - 正确使用 Web Font Loader 事件/非事件回调

转载 作者:行者123 更新时间:2023-11-28 15:51:53 26 4
gpt4 key购买 nike

我在回答这个应该是相当明显的问题时遇到了麻烦。

Webfont Loader 文档指出将其放置为“HTML 文档 <head> 中的第一个元素”。它还包括事件/非事件回调选项,这些选项在加载字体或加载失败/超时时调用。

问题是,如果我将回调函数放在紧随 后的脚本 block 中,则回调函数当时是未定义的。

我的代码如下:

<head>
<script type="text/javascript">
WebFontConfig = {
google: { families: [ 'Playball::latin' ] },
active: doActive(),
inactive: doInactive()
};
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})(); </script>

// ... other code ...

<script>
function doActive() {
// ...
}
function doInactive() {
// ...
}
</script>
</head>

这只是默认的 Google 代码,加上两个回调。

我看到的唯一明显的选择是在定义其他函数后包含 webfont 加载器,但这并不优雅。我知道有更好的解决方案,但我的 Google-fu 没有找到它。

最佳答案

你的错误是直接执行回调。

 WebFontConfig = {
google: { families: [ 'Playball::latin' ] },
active: doActive(), // () executes directly
inactive: doInactive()
};

您应该尝试这样做:

 WebFontConfig = {
google: { families: [ 'Playball::latin' ] },
active: doActive, // Only the function. The library will execute the function
inactive: doInactive
};

如果库执行您的回调,该函数应该可用

关于javascript - 正确使用 Web Font Loader 事件/非事件回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20249770/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com