Google字体API是Google提供的一项免费服务,允许网站通过简单的CSS或JavaScript代码引用Google服务器上的字体资源,而无需自行托管字体文件。
// 测试Google字体API是否可达
fetch('https://fonts.googleapis.com/css?family=Roboto')
.then(response => console.log('API响应:', response.status))
.catch(error => console.error('连接失败:', error));
<!-- 正确引用示例 -->
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Roboto', sans-serif;
}
</style>
<!-- 使用本地托管的字体作为备用 -->
<style>
@font-face {
font-family: 'Roboto';
src: local('Roboto'),
url('/fonts/Roboto-Regular.woff2') format('woff2'),
url('/fonts/Roboto-Regular.woff') format('woff');
font-weight: 400;
font-style: normal;
}
body {
font-family: 'Roboto', Arial, sans-serif;
}
</style>
如果Google字体API在您所在地区不可用,可以考虑使用国内CDN镜像服务(需自行寻找可靠的服务商)。
打开开发者工具(F12)查看网络请求,确认字体资源是否成功加载。
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Roboto&text=Hello" rel="stylesheet">
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
如果以上方法都无法解决问题,建议考虑完全自托管字体文件,以消除对外部API的依赖。