wp-media / wp-rocket

Performance optimization plugin for WordPress
https://wp-rocket.me
GNU General Public License v2.0
700 stars 219 forks source link

Optimize Google Fonts - Add a preconnect resource hint for fonts.googleapis.com #5821

Open vmanthos opened 1 year ago

vmanthos commented 1 year ago

Is your feature request related to a problem? Please describe.

Currently, we are adding a preconnect hint for fonts.gstatic.com when the Optimize Google Fonts feature is enabled: https://github.com/wp-media/wp-rocket/blob/b8d34c4b9f8ebbbe9cd9317d826c84dc15ac5493/inc/Engine/Optimization/GoogleFonts/Subscriber.php#L79-L82

We should do the same for fonts.googleapis.com. See Additional context.

Describe the solution you'd like

preconnect fonts.googleapis.com when Google Fonts are optimized.

Describe alternatives you've considered

N/A

Additional context

This is an example of the snippet provided by Google Fonts to add a font on a site:

<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=Cairo:wght@400;700&display=swap" rel="stylesheet">

Both fonts.gstatic.com and fonts.googleapis.com have preconnect resource hints.

Acceptance Criteria

  1. If Google Fonts are optimised by us we should preconnect fonts.googleapis.com domain
  2. If Google Fonts are not optimised by us (no Google Fonts in the source, or disabled by filter) we should not preconnect this domain
  3. If Used CSS is injected to the source, we should not preconnect fonts.googleapis.com domain
  4. If Removed Unused CSS feature is enabled, but the Used CSS is not injected (failed, or not generated yet), we should preconnect fonts.googleapis.com domain
piotrbak commented 1 year ago

@vmanthos This should happen only when Used CSS is not present on the page, right?

vmanthos commented 1 year ago

This should happen only when Used CSS is not present on the page, right?

If we can detect that Google Fonts are preloaded while used CSS is applied, I think it would be nice to add the preconnect hint for fonts.googleapis.com/. We won't need the one for fonts.googleapis.com.