google font api что это

Developer API

The Developer API gives access to the metadata for all families served by Google Fonts. It allows apps to query Google Fonts for the available font families. The REST API supplies data in the JSON format that includes the styles and scripts (called subsets in Google Fonts) in each family. The API can sort the list of families alphabetically, by date added, by number of styles, by trend, or by popularity.

Audience

This document is intended for web and application developers. Using the Developer API requires knowledge of JavaScript.

A quick example

To retrieve the dynamic list of fonts offered by the Google Fonts service, send the following request:

A sample of the result would look like this:

Identifying your application to Google

Your application needs to identify itself every time it sends a request to the Google Fonts Developer API, by including an API key with each request.

Acquiring and using an API key

Or create one in the Credentials page.

After you have an API key, your application can append the query parameter key= yourAPIKey to all request URLs.

The API key is safe for embedding in URLs; it doesn’t need any encoding.

Details

The JSON response (refer to sample above) is composed of an array named «items» which contains objects with information about each font family.

A family object is composed of 4 fields:

By combining the information for each family it is easy to create a Fonts API request. For example assuming we have a reference to the family object for Anonymous Pro:

The list of families is returned in no particular order by default. It is possible however to sort the list using the sort parameter:

The possible sorting values are:

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Get Started with the Google Fonts API

This guide explains how to use the Google Fonts API to add fonts to your web pages. You don’t need to do any programming; all you have to do is add a special stylesheet link to your HTML document, then refer to the font in a CSS style.

A quick example

Here’s an example. Copy and paste the following HTML into a file:

Then open the file in a modern web browser. You should see a page displaying the following, in the font called Tangerine:

That sentence is ordinary text, so you can change how it looks by using CSS. Try adding a shadow to the style in the previous example:

You should now see a drop shadow under the text:

And that’s only the beginning of what you can do with the Fonts API and CSS.

Overview

You can start using the Google Fonts API in just two steps:

Add a stylesheet link to request the desired web font(s):

Style an element with the requested web font, either in a stylesheet:

or with an inline style on the element itself:

For a list of fonts you can use, see Google Fonts.

Specifying font families and styles in a stylesheet URL

To determine what URL to use in your stylesheet link, start with the Google Fonts API base URL:

Then, add the family= URL parameter, with one or more font family names and styles.

For example, to request the Inconsolata font:

To request multiple font families, separate the names with a pipe character ( | ).

For example, to request the fonts Tangerine, Inconsolata, and Droid Sans:

Requesting multiple fonts allows you to use all of those fonts in your page. (But don’t go overboard; most pages don’t need very many fonts, and requesting a lot of fonts may make your pages slow to load.)

To find out which styles and weights are available for a given font, see the font’s listing in Google Fonts.

For each style you request, you can give either the full name or an abbreviation; for weights, you can alternatively specify a numerical weight:

Style Specifiers
italic italic or i
bold bold or b or a numerical weight such as 700
bold italic bolditalic or bi

For example, to request Cantarell italic and Droid Serif bold, you could use any of the following URLs:

Use font-display

font-display lets you control what happens while the font is unavailable. Specifying a value other than the default auto is usually appropriate.

Pass the desired value in the querystring display parameter:

Specifying script subsets

Some of the fonts in the Google Font Directory support multiple scripts (like Latin, Cyrillic, and Greek for example). In order to specify which subsets should be downloaded the subset parameter should be appended to the URL.

For example, to request the Cyrillic subset of the Roboto Mono font, the URL would be:

To request the Greek subset of the Roboto Mono font, the URL would be:

To request both Greek and Cyrillic subsets of the Roboto Mono font, the URL would be:

The Latin subset is always included if available and need not be specified. Please note that if a client browser supports unicode-range (http://caniuse.com/#feat=font-unicode-range) the subset parameter is ignored; the browser will select from the subsets supported by the font to get what it needs to render the text.

For a complete list of available fonts and font subsets please see Google Fonts.

Optimizing your font requests

Oftentimes, when you want to use a web font on your website or application, you know in advance which letters you’ll need. This often occurs when you’re using a web font in a logo or heading.

Читайте также:  Что значит сублимация простым языком

In these cases, you should consider specifying a text= value in your font request URL. This allows Google to return a font file that’s optimized for your request. In some cases, this can reduce the size of the font file by up to 90%.

As with all query strings, you should URL-encode the value:

This feature also works for international fonts, allowing you to specify UTF-8 characters. For example, ¡Hola! is represented as:

Enabling font effects (Beta)

When making headers or display texts on your website, you’ll often want to stylize your text in a decorative way. To simplify your work, Google has provided a collection of font effects that you can use with minimal effort to produce beautiful display text. For example:

To use this beta feature, simply add effect= to your Google Fonts API request and add the corresponding class name to the HTML element(s) that you want to affect. In our example above, we used the shadow-multiple font effect, so the request would look like:

You can request multiple effects by separating the effect names with a pipe character ( | ).

Here is a complete listing of all the font effects that we offer:

Effect API Name Class Name Support
Anaglyph anaglyph font-effect-anaglyph Chrome, Firefox, Opera, Safari
Brick Sign brick-sign font-effect-brick-sign Chrome, Safari
Canvas Print canvas-print font-effect-canvas-print Chrome, Safari
Crackle crackle font-effect-crackle Chrome, Safari
Decaying decaying font-effect-decaying Chrome, Safari
Destruction destruction font-effect-destruction Chrome, Safari
Distressed distressed font-effect-distressed Chrome, Safari
Distressed Wood distressed-wood font-effect-distressed-wood Chrome, Safari
Emboss emboss font-effect-emboss Chrome, Firefox, Opera, Safari
Fire fire font-effect-fire Chrome, Firefox, Opera, Safari
Fire Animation fire-animation font-effect-fire-animation Chrome, Firefox, Opera, Safari
Fragile fragile font-effect-fragile Chrome, Safari
Grass grass font-effect-grass Chrome, Safari
Ice ice font-effect-ice Chrome, Safari
Mitosis mitosis font-effect-mitosis Chrome, Safari
Neon neon font-effect-neon Chrome, Firefox, Opera, Safari
Outline outline font-effect-outline Chrome, Firefox, Opera, Safari
Putting Green putting-green font-effect-putting-green Chrome, Safari
Scuffed Steel scuffed-steel font-effect-scuffed-steel Chrome, Safari
Shadow Multiple shadow-multiple font-effect-shadow-multiple Chrome, Firefox, Opera, Safari
Splintered splintered font-effect-splintered Chrome, Safari
Static static font-effect-static Chrome, Safari
Stonewash stonewash font-effect-stonewash Chrome, Safari
Three Dimensional 3d font-effect-3d Chrome, Firefox, Opera, Safari
Three Dimensional Float 3d-float font-effect-3d-float Chrome, Firefox, Opera, Safari
Vintage vintage font-effect-vintage Chrome, Safari
Wallpaper wallpaper font-effect-wallpaper Chrome, Safari

Note: Some of the font effects (e.g. 3d) do not scale particularly well, and tend to look best when used with larger font sizes. Additionally, you might want to style the fonts further, such as changing the color of the text to match your page.

There are many more ways to style your fonts, and many things are possible through CSS. We are simply providing a few ideas to get you started. For more ideas, try Google searching «css text effects» and browse through many of the ideas that are already on the web!

Further reading

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Frequently Asked Questions

How do I contact Google Fonts?

For real time issues, tweet us @googlefonts. For technical questions, post an issue on our GitHub issue tracker. If you need to contact us privately, email fonts@google.com.

Can I use these fonts commercially: to make a logo, for print media, for broadcast, ebooks, apps, or sewing machines and apparel?

How do I find fonts that support my language?

Go to fonts.google.com, click the «Language» filter, and use the drop-down menu to select the writing system used by the language that you’re looking for.

Can I use CSS features like text shadows and rotation with web fonts?

Absolutely. Any CSS feature that can be applied to text on the web works well with all kinds of fonts – web fonts, local fonts, and system fonts.

What are variable fonts?

Variable fonts are a recent evolution in typography. This format lets you create custom variations of a typeface from a few small files instead of having a separate font file for every style, width, or weight. Learn more from Web Fundamentals.

How do I upload a font to Google Fonts?

We review submissions on GitHub. Please see our contribution requirements for all the details.

How can I use the Google Fonts GitHub?

You can use our GitHub to download font files to install or self host, file issues you’ve encountered with any aspect of our product, and even contribute your own fonts. Check it out at github.com/google/fonts.

What does using the Google Fonts API mean for the privacy of my users?

The Google Fonts API is designed to limit the collection, storage, and use of end-user data to only what is needed to serve fonts efficiently.

Use of Google Fonts API is unauthenticated. No cookies are sent by website visitors to the Google Fonts API. Requests to the Google Fonts API are made to resource-specific domains, such as fonts.googleapis.com or fonts.gstatic.com. This means your font requests are separate from and don’t contain any credentials you send to google.com while using other Google services that are authenticated, such as Gmail.

In order to serve fonts quickly and efficiently with the fewest requests, responses are cached by the browser to minimize round-trips to our servers.

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.

Читайте также:  daniel klein что это

The font files are cached for 1 year.

Google Fonts logs records of the CSS and the font file requests, and access to this data is kept secure. Aggregate usage numbers track how popular font families are and are published on our analytics page. We use data from Google’s web crawler to detect which websites use Google fonts. To learn more about the information Google collects and how it is used and secured, see Google’s Privacy Policy.

Where is the homepage sample text from?

«A shining crescent far beneath the flying vessel» – Triplanetary, E. E. Smith

«All their equipment and instruments are alive» – Mr. Spaceship, Philip K. Dick

«Almost before we knew it, we had left the ground» – A Trip to Venus, John Munro

«I watched the storm, so beautiful yet terrific» – Frankenstein, Mary Shelley

«It was going to be a lonely trip back» – Youth by Isaac Asimov

«Mist enveloped the ship three hours out from port» – The Jewels of Aptor, Samuel R. Delany

«My two natures had memory in common» – Strange Case of Dr Jekyll and Mr Hyde, Robert Louis Stevenson

«Silver mist suffused the deck of the ship» – The Jewels of Aptor, Samuel R. Delany

«The face of the moon was in shadow» – Mr. Spaceship, Philip K. Dick

«The recorded voice scratched in the speaker» – Deathworld, Harry Harrison

«The sky was cloudless and of a deep dark blue» – A Trip to Venus, John Munro

«The spectacle before us was indeed sublime» – A Trip to Venus, John Munro

«Then came the night of the first falling star» – The War of the Worlds, H. G. Wells

«Waves flung themselves at the blue evening» – The Jewels of Aptor, Samuel R. Delany»

«A red flair silhouetted the jagged edge of a wing» – The Jewels of Aptor, Samuel R. Delany

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Руководство по Google Font API

Несмотря на новые веб-технологии и стартапы, ещё до недавнего времени мы испытывали недостаток в богатой и красивой веб-типографии.

Хотя у нас достаточно широкий выбор гарнитур, мы могли использовать только определённый набор правильных шрифтов, установленных и поддерживаемых большинством компьютеров — эти шрифты были известны как — Безопасные веб-шрифты (Web-safe fonts).

Веб-типография против печатной типографии

При создании контента на традиционных носителях (газеты, журналы, книги) в использовании типографии вас ограничивает только творческий потенциал.

Но сейчас, разделение между печатными и виртуальными носителями сокращается. Сейчас @font-face поддерживают многие современными браузеры (включая Internet Explorer с версии IE4.0).

Введение в Google Font API

Google Font Directory и Google Font API — это бесплатные веб-сервисы от Google, которые предоставляют владельцам сайтов возможность использовать различные шрифты простым, удобным и эффективным способом.

Итак, давайте окунёмся в неисследованный потенциал Google Font API.

Что такое Google Font API?

Вы много путешествовали по интернету, но на многих ли сайтах или блогах вы видели нестандартные шрифты?

Давайте определим нестандартные шрифты, которые не входят в число безопасных (Arial, Helvetica, Verdana, Georgia и Times New Roman).

Google Font API — это веб-сервис, предоставляющий высококачественные открытые (open source) шрифты, которые легко могут быть использованы в вашем дизайне.

Мы надеемся, что коллекция шрифтов продолжит расти, чтобы у нас был ещё больший выбор различных гарнитур.

Преимущества использования Google Font API

Если вы ещё решаете, использовать ли Google Font API, то вот некоторые из его преимуществ.

Использование HTML текста

Кроме того, вам не нужно будет изменять существующий контент — вы только обновите свои CSS таблицы.

Доступность

Поскольку вы используете HTML текст, а не изображение или фон CSS, то это не затрагивает людей, использующих программы для экранного чтения.

Надёжная инфраструктура и снижение нагрузки на ваш сервер

Так как загрузка вашего @font-face использует надёжную инфраструктуру Google, вы можете быть уверены в том, что обслуживание файлов шрифтов будет быстрым, а вы сможете снизить нагрузку на собственный сервер.

Как пользоваться Google Font API

Вам не нужно быть профессиональным веб-разработчиком, чтобы использовать Google Font API. Всё, что нужно для этого сделать — это добавить один элемент stylesheet link на свою страницу, после чего, вы можете начинать использовать этот шрифт в CSS.

Вот обобщённый процесс использования Google Font API:

Шаг 1: Добавление ссылки в таблицу стилей с выбранным шрифтом

Для начала зайдите в коллекцию шрифтов Google, чтобы посмотреть, какие шрифты доступны для использования. Вот основной формат для включения определённого шрифта:

Источник

До свидания, Google Fonts. Последний аргумент

Шрифты Google Fonts страшно популярны. Их загружают более 42,8 миллиона сайтов, в том числе Хабр. Библиотека Google Fonts содержит 1023 свободных шрифта и программные интерфейсы для их внедрения через CSS. Очень удобно, казалось бы.

Во многих статьях отмечалось, в какую цену обходятся многочисленные запросы через API. Совет самостоятельно хостить шрифты дают много лет. Даже сама Google давала такой совет на конференции Google I/O 2018 года в выступлении на тему веб-производительности.

Так почему же многие до сих пор загружают шрифты через Google Fonts API? Ну, был последний аргумент — кэширование. Мол, благодаря общему CDN пользователю не нужно скачивать шрифт заново с каждого сайта. Однако в октябре 2020 года этот аргумент перестал работать. Теперь шрифты Google Fonts больше не кэшируются!

Читайте также:  что делать если в кроссовках жарко

Свой хостинг быстрее

По своей природе Google Fonts даже со всеми оптимизациями не может загружаться клиенту быстрее, чем с родного хостинга. Сравнительные бенчмарки можно посмотреть, например, здесь и здесь.


Загрузка Google Fonts без preconnect

Оптимизированная загрузка Google Fonts с опцией preconnect (подсказка для браузера заранее подключиться к домену fonts.gstatic.com, чтобы ускорить установку соединения в будущем):


Загрузка Google Fonts с preconnect

Дело в том, что Google всегда запрашивает с сервера таблицу стилей:

Она загружается в любом случае. А уже потом декларация @font-face говорит браузеру использовать локальную (кэшированную) версию шрифта при наличии таковой. По крайней мере, так было раньше:

Но в последнее время Google удалила фунцию local() из @font-face в Google Fonts! То есть шрифты Google Fonts теперь не могут считываться локально, если использовать API.

Из-за дополнительных запросов в к серверу Google возникает лишняя задержка.


Загрузка с fonts.gstatic.com с опцией preconnect


Загрузка со своего хостинга с опцией preload

Как видим, во втором случае запросы к fonts.gstatic.com отсутствуют, что сразу сокращает время загрузки страницы. Это самый оптимальный вариант.

Размещение шрифтов Google Fonts у себя

Марио Ранфтль создал очень полезный справочник google-webfonts-helper. Здесь можно выбрать конкретные шрифты из библиотеки Google Fonts, нужные наборы символов, начертания, посмотреть поддержку в браузерах — и получить код CSS и непосредственно сами файлы. То есть можно перенести нужные шрифты на свой хостинг в пару нажатий кнопки мыши.

Выбираем шрифт, наборы символов и стили. Чем больше стилей мы выберем, тем больше объём скачивания для клиента.

У разных семейств шрифтов разные уровни проработки. Например, кириллицу поддерживают только 118 из 1023 шрифтов на Google Fonts. Не все шрифты поддерживают полный набор начертаний.


Самое популярное в коллекции Google Fonts семейство шрифтов Roboto

И получаем код CSS для вставки. Вариант для поддержки максимальным количеством браузеров, в том числе устаревшими:

Вариант для поддержки только современными браузерами:

Как видим, здесь функция local() сохранилась, в отличие от официальных стилей Google.

Современным браузерам достаточно файлов WOFF и WOFF2, а для устаревших нужны ещё форматы TTF, EOT и SVG. Например, один из вариантов — отказаться от «устаревших» форматов, отдавать только WOFF и WOFF2, а если у клиента старый браузер, то страница отобразится системным шрифтом, без загрузки лишних файлов.

В библиотеке Google Fonts шрифты оптимизируются, там ресурсы минимального размера. Так что для своего хостинга лучше брать файлы именно из этого источника.

Оптимизация загрузки

Следует иметь в виду, что в таком случае браузер загрузит ресурсы в обязательном порядке независимо от того, понадобятся они ему впоследствии или нет.

Последний аргумент

Итак, единственным аргументом в пользу Google Fonts была быстрая и надёжная сеть доставки контента (CDN) с кэшированием. Google владеет точками присутствия у всех крупных провайдеров по всему миру.

Популярные шрифты вроде Open Sans и Roboto используются на многих сайтах. Идея была в том, что пользователю достаточно посетить один такой сайт — ресурсы загружаются один раз и хранятся в кэше браузера, так что при заходе на другой сайт они не будут скачиваться повторно.

Но теперь так больше не работает. Начиная с версии Chrome 86, которая вышла в октябре 2020 года, межсайтовые ресурсы вроде шрифтов больше не делят общий CDN из-за разделённого браузерного кэша (partitioned browser cache).

В блоге Google объясняется смысл этой функции, которая реализована для защиты от межсайтового трекинга. То есть для приватности. К сожалению, ради этого пришлось пожертвовать производительностью.

При запросе ресурсов с CDN раньше в качестве ключа кэша использовался соответствующий URL ресурса (того же шрифта). Таким образом, если два разных сайта запрашивали картинку или шрифт с одного и того же URL, то этот ресурс не скачивался дважды.

Долгое время такой механизм хорошо работал с точки зрения производительности. Однако в последнее время появились идеи, как его эксплуатировать во вред людям. Оказалось, что по отклику браузера можно определить, что браузер или 1) скачивает ли ресурс заново, или 2) ресурс уже есть в кэше. Соответственно, в достаточно продвинутой атаке можно понять, какие сайты этот браузер посещал в прошлом. А исследователи доказали, что по истории посещённых сайтов/страниц можно с высокой степенью достоверности идентифицировать личность пользователя, даже если браузер запущен в режиме инкогнито, блокируется JavaScript и удаляются куки. То есть история посещённых страниц — тоже подходящий вариант для фингерпринтинга.

Кроме фингерпринтинга, становится возможным межсайтовый трекинг, то есть отслеживание пользователей с уникальным ID на всех сайтах, которые участвуют в этой системе.

В такой ситуации Google ничего не оставалось, кроме как пожертвовать производительностью — и запретить в браузере совместное кэширование ресурсов, в том числе шрифтов.

В новой реализации в качестве ключа кэша используется не только URL ресурса, а новый составной параметр Network Isolation Key. Он состоит из трёх частей: домен верхнего уровня, домен текущего фрейма и URL ресурса.

Таким образом, при посещении нового сайта тот же шрифт будет скачиваться заново с того же URL.

Разделённый кэш присутствует в Safari c 2013 года. Остальные подтянулись только сейчас:

Вслед за Chrome разделённый кэш планируют реализовать и разработчики Firefox, а затем с большой степенью вероятности и других браузеров, основанных на Chromium.

Таким образом, браузер всегда будет скачивать шрифты Google Fonts заново для каждого сайта. Последний аргумент в пользу использования общего кэша теперь не работает.

Что делать?

Печально, что из-за приватности приходится жертвовать производительностью и делать лишние сетевые запросы.

Что можно сделать пользователю, чтобы не скачивать шрифты каждый раз с каждого сайта?

На правах рекламы

Мощные серверы в аренду на базе новейших процессоров AMD EPYC для размещения веб-проектов любой сложности, от лендингов до крупных новостных порталов или интернет-магазинов. Создайте собственный тарифный план в пару кликов и приступите к работе уже через минуту!

Источник

Сказочный портал