如何在Google Chrome中强制重新加载字体

时间:2016-12-25 22:33:24

标签: javascript html css google-chrome fonts

有一个带自定义字体的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.

1 个答案:

答案 0 :(得分:0)

似乎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 += " ";
  }
});