将 Ajax 内容加载到 div (Wordpress) 时,不会事先加载字体



我在Wordpress中使用了一个JS函数和Ajax,当点击某些元素时,它会在模态div中加载帖子的内容。JS函数看起来像这样:

function openProjectModal($that) {
var post_id = $that.attr("rel");
window.location.hash = $that.data("slug");
$("#content-projects").load(localization.ajax_url+"?action=load_more_post&pid="+post_id,{},function(data,status){
initImageLoad();
});
}

functions.php中创建标记的函数如下所示:

function load_more_post_callback() {
if( isset($_GET["pid"]) ){
$post = get_post( $_GET["pid"] );
if( $post instanceof WP_Post ) {
echo '<div id="close"></div>';
echo '<section id="title-projects"><h1>' . get_the_title($post->ID) . '</h1><p class="project-meta">' . get_field("location", $post->ID) . ' (' . get_field("year", $post->ID) . ')</p></section>';
} else {
// nothing found with the post id
}
} else {
// no post id
}
wp_die();
}

新内容中的h1通过 CSS 应用了初始页面上未使用的字体。因此,当div 加载来自 Ajax 调用的内容时,字体的加载会出现延迟,这看起来很奇怪。它从空白到Times New Roman,再到正确的字体。当我关闭模态并打开一个新模态时,字体会立即加载到应有的状态。我猜它从第一次加载中被缓存。

我已经在整个站点上使用的CSS中添加了字体,但似乎浏览器只加载标记中实际使用的字体,因为这种对于Ajax内容唯一的字体会在加载Ajax内容时加载。

不过,我只在 Safari 中注意到了这一点,但如果有一个解决方法,即使它只是 Safari 中的一个特殊问题,那就太好了。关于如何在显示字体之前预加载字体的任何想法?

在你的模态中,只需做

<h2 class="myTitleFont">Title</h2>

那么在css中,你可以做到:

.myTitleFont {
font-family. "yourFont";
}

或者,如果确实必须:

.myTitleFont {
font-family: "yourFont" !important;
}

显然,">您的字体"是您font的名称。

我仍然认为这只是一个 css 问题,但是,在打开并运行时为您的模态创建一个回调:

$(".modal").on.("show", function(){
addGoogleFont();
});
function addGoogleFont() {
$("head").append("<link href='https://fonts.googleapis.com/css?family=" + FontName + "' rel='stylesheet' type='text/css'>");
$(".modal h2").css("opacity", "1");
}

并将您的模态 h2 设置为不透明度 0,这样您才会看到它,直到

.modal h2 {
opacity: 0;
}

最新更新