Skip to content

Instantly share code, notes, and snippets.

@m-allanson
Last active January 13, 2022 23:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m-allanson/25c24f4790c7768a06ed52e160ab576b to your computer and use it in GitHub Desktop.
Save m-allanson/25c24f4790c7768a06ed52e160ab576b to your computer and use it in GitHub Desktop.
/**
* Creates a preload link pointing to myFonts' licence counting url. This
* allows hits to the site to register as font requests with myFonts, but
* ensures that we are not blocking CSS rendering by waiting for this request
* to complete.
*
* This avoids having to include the following in a CSS file:
* @import url("//hello.myfonts.net/count/<id>");
*
* Refs:
* https://stackoverflow.com/questions/23045705/how-the-licensed-web-font-is-getting-rendered
* https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content
*/
const React = require("react");
exports.onRenderBody = function({ setHeadComponents }, pluginOptions) {
setHeadComponents([
React.createElement("link", {
key: "fonts",
href: `//hello.myfonts.net/count/${pluginOptions.myFontsId}`,
rel: "preload",
as: "style"
})
]);
};
@abrman
Copy link

abrman commented Jan 11, 2022

Thank you for sharing this!
Also pretty sure there's a missing trailing back-tick (`) on :21

@m-allanson
Copy link
Author

No problem, I'm glad it was helpful.

And yep, good spot on the missing back-tick. I've updated the gist to fix it. Thank you!

@abrman
Copy link

abrman commented Jan 13, 2022

I know this is not a help forum, but I struggled with the pluginOptions.myFontsId implementation. I've read in docs that I can set it up in gatsby-config.js but wasn't able to figure it out - hardcoded it for my use-case. Was wondering how'd you go about setting it up in gatsby-config if you're willing to share :)

@m-allanson
Copy link
Author

I don't actually remember how I did this 😬 and I don't have access to the code that I wrote this for any more. Doing a bit of digging, I'm guessing that this gatsby-ssr.js file was part of a local plugin.

You could then pass the config options in as part of the plugin config. I found an example site with that approach: https://github.com/gatsbyjs/gatsby/tree/master/examples/using-plugin-options. And there's a bit more info on local plugins here: https://github.com/gatsbyjs/gatsby-starter-plugin.

tbh hardcoding the id seems like a nice and simple way to do it. I hope that helps!

@abrman
Copy link

abrman commented Jan 13, 2022

Thank you! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment