有一个带有自定义字体的html页面。由于某些原因,服务器有时不提供字体。在这种情况下,我需要使用相同的URL重新加载字体。
我希望从页面中删除所有样式,然后再将其重新添加会有所帮助。
但是这种方法在Google Chrome中不起作用。如何解决?
我对不重新加载页面的方式感兴趣。
测试代码示例(将nodejs用作服务器):https://cloud.mail.ru/public/JeBp/hcaRZgGSC
<!doctype html>
<title>Font test</title>
<script>document.cookie = 'send-the-font=0'</script>
<style>
@font-face {
font-family: 'Aref Ruqaa';
font-style: normal;
font-weight: 400;
src: url(ArefRuqaa-Regular.ttf);
}
body {
font-family: 'Aref Ruqaa';
font-style: normal;
color: blue;
}
</style>
<p>Just some text</p>
<button id="retry">Retry</button>
<script>
document.getElementById('retry').addEventListener('click', function () {
document.cookie = 'send-the-font=1';
var style = document.querySelectorAll('style');
for (var q=0; q<style.length; ++q) {
style[q].remove();
}
setTimeout(function () {
for (var q=0; q<style.length; ++q) {
document.head.appendChild(style[q]);
}
}, 1000);
});
</script>
var http = require('http');
var fs = require('fs');
http.createServer(function (request, response) {
var file = decodeURIComponent(request.url.substr(1));
var headers = {};
console.log(file);
switch(file) {
case "":
case "index.html":
file = "index.html";
headers['Content-Type'] = 'text/html; charset=UTF-8';
break;
case "favicon.ico":
headers['Content-Type'] = 'image/x-icon';
break;
case "ArefRuqaa-Regular.ttf":
headers['Content-Type'] = 'font/opentype';
if (request.headers.cookie && request.headers.cookie.indexOf('send-the-font=1') !== -1) {
console.log(' allowed');
break;
}
/* Falls through */
default:
console.log(' 404');
response.writeHead(404, { 'Content-Type': 'text/plain' });
response.end('Not found!');
return;
}
fs.stat(file, function (error, data) {
if (error) {
console.log(error);
response.writeHead(500, { 'Content-Type': 'text/plain' });
response.end('An error occured while loading file information :(');
} else if (!data.isFile()) {
response.writeHead(403, { 'Content-Type': 'text/plain' });
response.end('Not a file');
} else {
headers['Content-length'] = data.size;
response.writeHead(200, headers);
fs.createReadStream(file).pipe(response);
}
});
}).listen(8081);
PS:Same question in Russian.
最佳答案
好像Chrome浏览器对样式使用了一些缓存,并且如果再次添加具有相同内容的样式(无论是相同的样式标签,还是其他样式都无关紧要),则它不需要字体。
可以通过更新样式内容来解决:
document.getElementById('retry').addEventListener('click', function () {
document.cookie = 'send-the-font=1';
var style = document.querySelectorAll('style');
for (var q=0; q<style.length; ++q) {
style[q].innerHTML += " ";
}
});
关于javascript - 如何在Google Chrome浏览器中强制重新加载字体,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41324990/