How do I 'leverage browser caching' for Google fonts?
Asked Answered
S

7

48

I tested my site via Pingdom and got this:

enter image description here

I searched but couldn't find a solution to this. Does anyone know how I can get this 14 to 100?

Savaii answered 17/3, 2015 at 3:52 Comment(1)
DON'T download and self-host CSS to fix this issue. https://mcmap.net/q/352555/-how-do-i-39-leverage-browser-caching-39-for-google-fontsGlove
B
32

Since you cannot control Googles headers (including expiration headers), I can see only one solution – download these two stylesheets and fonts to your own hosting server, change HTML tags accordingly.

Then, you can set expiration headers (what Pingdom called 'lifetime') as you wish.

For example, open the first link:

/* latin */
@font-face {
  font-family: 'Montserrat';
  font-style: normal;
  font-weight: 400;
  src: local('Montserrat-Regular'), url(http://fonts.gstatic.com/s/montserrat/v6/zhcz-_WihjSQC0oHJ9TCYAzyDMXhdD8sAj6OAJTFsBI.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}

Download this .woff2 file and save it anywhere on your webserver. Copy & paste this piece of stylesheet into any of your own CSS files or HTML. Change the link from fonts.gstatic.com to your new URL.

Google serves these fonts with expiration time of 1 day. You could easily set it to 30 days now.

Baillargeon answered 17/3, 2015 at 4:3 Comment(11)
Thanks, I was hoping I wouldn't have to download the fonts, but I guess it's the only way. I wonder why Google, who actively encourages PageSpeed, doesn't even cache their own fonts. Anyway, thank you. I'll accept your answer in 2 min.Savaii
J82, perhaps, they want to be able to modify the fonts anytime quickly. However, as an individual user you may feel fine with the current version and cache it for months :)Baillargeon
Please don't do this. The content of the CSS files vary depending on the User Agent! If you open the file with Chrome and save the content, it will only work with Chrome etc! If you want to serve the CSS files from your own server, you need to provide a Crossbrowser solution. localfont.com has an option to generate this CSS for you for any font from google fonts. As well you can download the font files in all browser formats and serve those from your host as well, if you prefer.Vagus
@Vagus are you sure? when I open either of these CSS files, I don't see anything browser-dependent. Moreover, if Google thinks 1 day of caching is okay – there is probably no user agent tuning involved?Baillargeon
100% sure. Open it in another browser and the content looks completely different. Every browsers uses a different font format. TTF, WOFF/WOFF2, EOT and SVG are delivered depending on the user agent. Here is a bit outdated article describing it: ijotted.blogspot.com/2012/05/… The differences I know of are that SVG now is fixed and used by mobile Safari (iOS) and WOFF2 is being used instead of WOFF in some cases.Vagus
As for the caching argument: When you look at the actual headers, you can see the cache control is private: Cache-Control: private, max-age=86400 which means it should only be cached by the browser itself, and not by a shared cache, e.g. Proxy, Router etc.Vagus
@Vagus but on other hand, some developers do include several formats of font, one after another? one could gather several formats from Google and combine them in "src" property of font-face. so, combining WOFF and TTF will probably cover majority of browsers?Baillargeon
Yes, that is what localfont.com will actually do. It generates the cross browser CSS and provides all font files as a zip for download. It seems a bit broken though, doesn't work with all fonts and Montserrat unfortunately is one of them. In that case you can do it manually. The CSS template can be used of any font as generated by the site. But the font files then need to be downloaded manually. The above article shows which Browsers you can use and how to fake the User Agent to download all fonts.Vagus
When tinkering with the CSS yourself take care of IE. Of course there is some CSS hack in place to make it work in that one. ;-)Vagus
FYI -- I use this tool for downloading Google Fonts for offline use. It's been a time-saver: google-webfonts-helper.herokuapp.com/fontsDeclivitous
See Paul Herberts response below for what really is the correct answer.Sherlock
E
53

Not a complete solution, but you can improve the situation by combining the two requests to one:

https://fonts.googleapis.com/css?family=Montserrat|Open+Sans

I do that for two fonts on one of my sites and score 86 versus your 14. Importantly, this is a genuine speedup, not just a hack to reduce an arbitrary score.

Esquivel answered 18/12, 2015 at 13:1 Comment(5)
This method is a genuine speedup (I think). The alternative method of placing the font on your own server (putting more load on your server) will more likely slow things down while showing a "100" on the test. Real performance > test scores.Thermostatics
Remember that you should change the pipe character | to the URL encoded string† equivalent of %7c, not doing so will throw an error in some circumstances‡. So the above example would render as https://fonts.google.com/css?family=Montserrat%7cOpen+Sans †: reference ‡: referenceStun
I wonder if this means fewer cache hits. All the fonts are cached all along the way, but for arbitrary combinations of variable length it is much less likely.Davilman
@Thermostatics "more load on server" is not a legit argument really. in modern times a basic nginx instance can serve huge amounts of static content. let alone nginx with appropriate cache headers. moreover, if you host font files on CDN like Cloudflare - you will definitely get content faster than from Google. Google Page Performance tool complains about Google resources, ironically :)))Baillargeon
But this doesn't mean first look for Montserrat if not available then look for Open+Sans?Lyndes
B
32

Since you cannot control Googles headers (including expiration headers), I can see only one solution – download these two stylesheets and fonts to your own hosting server, change HTML tags accordingly.

Then, you can set expiration headers (what Pingdom called 'lifetime') as you wish.

For example, open the first link:

/* latin */
@font-face {
  font-family: 'Montserrat';
  font-style: normal;
  font-weight: 400;
  src: local('Montserrat-Regular'), url(http://fonts.gstatic.com/s/montserrat/v6/zhcz-_WihjSQC0oHJ9TCYAzyDMXhdD8sAj6OAJTFsBI.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}

Download this .woff2 file and save it anywhere on your webserver. Copy & paste this piece of stylesheet into any of your own CSS files or HTML. Change the link from fonts.gstatic.com to your new URL.

Google serves these fonts with expiration time of 1 day. You could easily set it to 30 days now.

Baillargeon answered 17/3, 2015 at 4:3 Comment(11)
Thanks, I was hoping I wouldn't have to download the fonts, but I guess it's the only way. I wonder why Google, who actively encourages PageSpeed, doesn't even cache their own fonts. Anyway, thank you. I'll accept your answer in 2 min.Savaii
J82, perhaps, they want to be able to modify the fonts anytime quickly. However, as an individual user you may feel fine with the current version and cache it for months :)Baillargeon
Please don't do this. The content of the CSS files vary depending on the User Agent! If you open the file with Chrome and save the content, it will only work with Chrome etc! If you want to serve the CSS files from your own server, you need to provide a Crossbrowser solution. localfont.com has an option to generate this CSS for you for any font from google fonts. As well you can download the font files in all browser formats and serve those from your host as well, if you prefer.Vagus
@Vagus are you sure? when I open either of these CSS files, I don't see anything browser-dependent. Moreover, if Google thinks 1 day of caching is okay – there is probably no user agent tuning involved?Baillargeon
100% sure. Open it in another browser and the content looks completely different. Every browsers uses a different font format. TTF, WOFF/WOFF2, EOT and SVG are delivered depending on the user agent. Here is a bit outdated article describing it: ijotted.blogspot.com/2012/05/… The differences I know of are that SVG now is fixed and used by mobile Safari (iOS) and WOFF2 is being used instead of WOFF in some cases.Vagus
As for the caching argument: When you look at the actual headers, you can see the cache control is private: Cache-Control: private, max-age=86400 which means it should only be cached by the browser itself, and not by a shared cache, e.g. Proxy, Router etc.Vagus
@Vagus but on other hand, some developers do include several formats of font, one after another? one could gather several formats from Google and combine them in "src" property of font-face. so, combining WOFF and TTF will probably cover majority of browsers?Baillargeon
Yes, that is what localfont.com will actually do. It generates the cross browser CSS and provides all font files as a zip for download. It seems a bit broken though, doesn't work with all fonts and Montserrat unfortunately is one of them. In that case you can do it manually. The CSS template can be used of any font as generated by the site. But the font files then need to be downloaded manually. The above article shows which Browsers you can use and how to fake the User Agent to download all fonts.Vagus
When tinkering with the CSS yourself take care of IE. Of course there is some CSS hack in place to make it work in that one. ;-)Vagus
FYI -- I use this tool for downloading Google Fonts for offline use. It's been a time-saver: google-webfonts-helper.herokuapp.com/fontsDeclivitous
See Paul Herberts response below for what really is the correct answer.Sherlock
D
30

First of all it's important to clarify the distinction between caching the Google Fonts CSS files and the actual font files. According to the Google Fonts FAQs, their font files are actually cached for a year. It's the CSS files that are cached for 24 hours:

Requests for CSS assets are cached for 1 day. This allows us to update a stylesheet to point to a new version of a font file when it’s updated, and ensures that all websites using fonts hosted by the Google Fonts API will be using the most updated version of each font within 24 hours of each release.

The font files themselves are cached for one year, which cumulatively has the effect of making the entire web faster: When millions of websites all link to the same fonts, they are cached after visiting the first website and appear instantly on all other subsequently visited sites. We do sometimes update font files to reduce their file size, increase coverage of languages, and improve the quality of their design. The result is that website visitors send very few requests to Google: We only see 1 CSS request per font family, per day, per browser.

I would recommend against hosting these CSS files yourself, as you will fall behind and not be using the latest versions of the fonts as they're updated.

However, there are a couple ways you can speed up the CSS request:

  1. As Mark mentioned in his answer, you can combine your two webfonts into one request: https://fonts.googleapis.com/css?family=Montserrat|Open+Sans
  2. If you're only using a certain styles of either font you can only load the styles you are actually using. Here we're loading all of Montserrat, but only loading three styles of Open Sans; regular (400), italic (400i), and bold (700): <link href="https://fonts.googleapis.com/css?family=Montserrat|Open+Sans:400,400i,700" rel="stylesheet">
Dag answered 4/4, 2017 at 18:38 Comment(6)
Actually, this is a better answer than the currently accepted one. Yes, the page speed tools complain about the css files cache control headers for the google web fonts, but you can safely ignore that as the css files are so small. Instead, focus on any resources outside of the google web fonts, and or do the above. I'm not going to worry about a single request or two that takes 50ms.Sherlock
What do you actually mean by "falling behind"? Are you, in all seriousness, expecting Google to change fonts more often than once in 5-10 years? Even if they do, do you actually believe most end users would care? I can hardly imagine somebody saying "oh, this Roboto 'e' letter is outdated, it should be one pixel wider, Google updated it 2 weeks ago". My solution is a workaround but it's legit, it works, it answers the question. It even has one advantage - full independence, you won't depend on external resources anymore (eg. intranet website)Baillargeon
That's fair Denis Mysenko. There are upsides and downsides to self hosting the fonts as well as Google Fonts. I have heard stories of fonts being updated in ways that break designs, and having less dependencies is great. On the other hand, sometimes font updates include new languages or smaller file sizes, and there can be caching benefits with CDNs. I see arguments for both approaches. I mostly wanted to point out that the 1 day caching period is applied to the CSS files and the font files themselves are cached for a year.Dag
But this doesn't mean first look for Montserrat if not available then look for Open+Sans?Lyndes
@PardeepJain, no, that's a special syntax allowed by Google Fonts to say "get both of these fonts:" https://mcmap.net/q/357096/-how-to-combine-google-fonts-imports I think you may be confused since it looks kind of like this code logic, but this is a very different thing: if(Montserrat || OpenSans) { doSomething(); }Dag
@Dag thank you for information. I'll check and ImplementLyndes
V
12

Be aware that you are not allowed to cache the css provided by Google more than 24 hours.

Just saying... according to Google's terms and conditions.

Vagrancy answered 12/8, 2017 at 6:50 Comment(0)
W
1

A fairly easy workaround would be to generate your own kit with Font Squirrel's Webfont Generator:

https://www.fontsquirrel.com/tools/webfont-generator

To be able to use this, you would need to download the fonts (Montserrat and Open Sans are both available on Font Squirrel) and add them to the generator. This can be used for adding further customization. (I've used it many times in cases where the font in Google Webfonts didn't have the necessary subsetting for Hungarian language even though it was available in the original font.)

Wendell answered 20/11, 2016 at 20:15 Comment(0)
G
1

I see many answers recommending you to download CSS and host yourself. DON'T do this as Google Fonts send different CSS for every browser based on the capability of the browser.

A quick solution can be Easy Fonts CDN that hosts all google fonts, plus provides some value addition like:

  1. Long expiry for CSS files. (This will resolve your issue of leverage browser caching)
  2. Easy debuggable font file names.
  3. Font Classes. You get easy to use CSS classes to use fonts in HTML, like <div class="font-open-sans"></div>, <div class="font-lato"></div>, etc. Complete reference is available here.
  4. An option for single all-in-one font file that you can include in all your projects and forget about looking up Google Fonts directory again and again to get new CSS URLs.
  5. Saves 1 extra DNS look because Google CSS is hosted in fonts.googleapis.com and actual font files are served from fonts.gstatic.com while Easy Fonts' CSS and font files are both served from pagecdn.io. If you use PageCDN for other opensource resources or if you host your own files on PageCDN, then this will actually save you 2 DNS lookups as all files are served on single host that is used for other files too, and there is no dedicated DNS lookup for fonts.
  6. Consistent CSS URLs. CSS for one font family will always load through one URL. This increases browser cache reuse. Google Fonts CSS files mix font family names and create endless possible CSS files. This reduces browser cache sharing across websites.

If you want to use just Open Sans and Montserrat fonts, here is your code:

<link href="https://pagecdn.io/lib/easyfonts/montserrat.css" rel="stylesheet" />
<link href="https://pagecdn.io/lib/easyfonts/open-sans.css" rel="stylesheet" />

If you want to use the all-in-one file, use:

<link href="https://pagecdn.io/lib/easyfonts/fonts.css" rel="stylesheet" />
Glove answered 17/7, 2019 at 10:37 Comment(0)
C
-1

What I got to work was adding PHP as a post-processor to my CSS files in my .htaccess file with the code (I'm using a custom .pcss file extension - just to make it separate from my simple CSS files):

<FilesMatch "\.pcss$">
SetHandler application/x-httpd-php
Header set Content-type "text/css"
</FilesMatch>

Then I used the following code in my CSS file to get and echo the content of the font URL I wanted.

<?php
echo file_get_contents("https://fonts.googleapis.com/css?family={FONT}");
?>
Curable answered 13/10, 2017 at 22:58 Comment(2)
such a terrible hack!Giacobo
Not recommended as this will only slow down the TTFB of the website. Also, Google loads CSS based on browser capabilities. With this approach, Google Fonts will send CSS based on whatever the useragent file_get_contents sends.Glove

© 2022 - 2024 — McMap. All rights reserved.