google / fonts

Font files available from Google Fonts, and a public issue tracker for all things Google Fonts
https://fonts.google.com
17.9k stars 2.6k forks source link

Loading all google fonts #2459

Open AbreezaSaleem opened 4 years ago

AbreezaSaleem commented 4 years ago

I need to provide the user the option to choose a google font from a list but I don't want to load all the fonts at once as that'll be inefficient. The call for fetching all the fonts has a size 77.8 kB.

Ideally, I would like to implement pagination in which I can provide the user with a dropdown of font types (monospace, serif, sans-serif etc) and after the user selects a type I can load 10 fonts from that font type for the first page and so on.

The problem is that I do not see any such filters provided in the google fonts api page. They have given us the option to sort our results but there's no option to filter or limit them. One possible solution that I have in my mind is that I store all the font labels in an object, where the keys will be the font types and the values will be an array of all the font labels of that particular type. And as the user selects a type I can select the first 10 font labels from the array (give I have chosen to display 10 fonts per page) and make a call to fetch all those fonts. And so on.

My data object could look like this:

const google_fonts: {
   monospace: ['Roboto Mono' ,'PT Mono' ,'Space Mono', ...],
   serif: ['PT Serif', 'Lora', 'Noto Serif', ...],
   sans-serif: [...],
   handwriting: [...],
   display: [...]
}

For example, if the user selects a monospace fonts, I would get the first 10 fonts from the array, append the labels in the google api call like this https://fonts.googleapis.com/css2family=Balsamiq+Sans&family=Open+Sans&family=Source+Sans+Pro and fetch the fonts.

But is there a better way to tackle this problem? Btw, I am trying to implement this in react.

davelab6 commented 2 years ago

No better way, but your idea is great!

You can also cache the developer API response on the server and paginate it there