Meta tags - ( X ) HTML - tags designed to provide structured metadata (additional, accompanying) about a web page . As a rule, they are indicated in the heading ( <head> ) (X) of the HTML document. The meta element accepts at least four attributes: content, http-equiv, name and scheme. Of these, only the content attribute and the exception tag revisit are required. Almost not standardized, developed by various services and browser providers at their discretion and regulated only by "inventors". Only a small part of the frequently used or "invented" long enough is recognized and processed relatively identically.
meta Element Example
[1] One use case for the meta tag is to specify HTTP headers that must be sent to the client before sending the web page itself. For example:
< meta http-equiv = "Content-Type" content = "text / html" />
This entry indicates that the page should be sent along with the Content-Type: text / html HTTP header. This header tells the browser or other program the type of document to send. Nevertheless, despite the fact that it was originally assumed that web servers would read meta tags inside web pages sent to the client and generate HTTP headers depending on their content, in practice this is not implemented in the most used web servers, respectively , web servers do not change the HTTP headers sent to the client, and the client (web browser) processes these meta tags independently [1] (in particular, data from meta tags can replace data obtained from HTTP headers [2] ).
In addition, meta tags can be used to tell the browser information about a document when HTTP headers are not available (for example, if the page is opened locally from disk and not loaded from a web server).
In general form, metadata is written in the following form: the meta tag specifies the name attribute and the content attribute associated with it, which describes some aspect of the web page, for example, keywords:
< meta name = "keywords" content = "wikipedia, encyclopedia" />
Meta Tag Functions
The main [2] feature of tags of this type is that they do not have displayed content, are located in the HEAD section and can contain any additional information for automatic processing by web clients - browsers, robots, and specialized software.
According to the purpose of the information provided, it is possible to conditionally distinguish the most widely used groups:
- Information about the document: authorship, sources, etc .;
- Information for search robots: keywords, a brief description, and [1] etc.;
- Instructions for browsers: code pages, cookies, automatic update intervals;
- Instructions for specialized software and various services, for example, an indication for parser programs of an address with a copy of the page data prepared for machine processing.
Meta Tag Groups
The most commonly used groups are: NAME , for general-purpose information, and HTTP-EQUIV , for indicating equivalent HTTP protocol headers in the body of a page.
HTML5 standardizes the charset attribute to indicate the encoding of the document (see example below). It is supported by all modern browsers and is correctly recognized by all search engines.
NAME
Author and Copyright
These tags are generally not used simultaneously. Tag function - identification of the author or affiliation of a document. The Author tag contains the name of the author of the web page, in the event that the site belongs to any organization, it is better to use the Copyright tag. Currently have extremely low relevance.
< meta name = "author" content = "Velimir Lisichkin" />
In addition, the Author and Copyright tags may contain an additional attribute “lang”, which allows you to define the language used when specifying the property value
< meta name = "copyright" lang = "ru" content = "BYBUL Velimir Lisichkin" />
Description
Designed to provide search engines with a brief description of page content for indexing and displaying accompanying information in the search results. Once the information from this tag was necessarily displayed in the search results and had a special weight during indexing, however, due to abuse, various search engines use different algorithms to assess the relevance of the description and content of the page specified in the tag, on the basis of which they can ignore the tag content .
Despite this, it is preferable to fill this tag, but keep in mind that the effective length of the text that can be placed in this tag by various search engines is set at your discretion and at the moment the recommended size is from 70 to 140 characters, and the maximum processed does not exceed 400.
It is authentically known:
- The content of the tag is taken into account and sometimes used to show in the search results. For example, as Yandex reports :
In some “magical” cases, even with this tag in the search results, the text from it is used as a page description. And this is not always the lead paragraph (first on the page).<meta name = "Description" content = "..." /> - the content of this tag can be used in snippets (site descriptions on the search results page);
- The effective content lengths taken into account by different search engines are different, but they are different search engines.
- The content of the tag affects the relevance score, but how exactly today, perhaps, even the developers themselves will not say, due to the fact that many different and complex algorithms are used to calculate relevance in all search engines. Therefore, developers in many articles and blogs, almost in chorus, say no, it does not affect in any way.
- All the same, you need to specify this tag, there are instructions on this in the help systems for webmasters of all major search engines.
In more detail in the article “ Description Tag Length for Yandex and for Google ”
< meta name = "description" content = "Wikipedia meta tags" />
Document-state
The Document-state meta tag can also be taken into account when indexing a page by search engines. Two values of the content attribute are taken into account - Static and Dynamic . The Static value indicates that the document changes extremely rarely, Dynamic (by default) - the page is created upon request and may change depending on additional conditions of the request. 20 years ago [ when? ] was important, at the moment it is difficult to imagine how the information from this tag can help a search engine that analyzes a page using a variety of parameters and using very complex and varied algorithms.
< meta name = "document-state" content = "Dynamic" />
Generator
This meta tag was once actively used by program developers to edit web pages - as a tag value, developers of such programs usually indicated their product name or other identifying information. A bit later, the CMS developers picked up the baton. Using this tag, some developers tried, if not to control, then at least roughly calculate the number of installations of their developments. However, soon, realizing that this makes life easier for all sorts of malicious "non-comrades", the most conscious developers refused this vicious practice. The fact is that having information about vulnerabilities and the internal structure of the system, it is easy enough to detect sites using it and take advantage of vulnerabilities for their far from specious purposes. In fact, for CMS - this tag is like a sign: come who wants and live at home.
It may make sense for some HTML editing programs that can take into account the features of other editors and use this to reverse engineer a saved page. For example, Macromedia DreamWeaver (now Adobe DreamWeaver), when opening HTML files created in Microsoft Word and Microsoft Excel, automatically deleted and modified the redundant and specific markup created by these programs.
Also, some tools inserted into the markup the data necessary for their further work and by this tag they controlled the probability of finding this data in the file. Today, for these purposes, trying to use other markers.
By and large for today - garbage. Currently, conscious citizens, as well as non-citizens, but conscious, are used extremely rarely, from the word "completely."
< meta name = "generator" content = "Macromedia Dreamviewer 4.0" />
Keywords
Used to provide data to search engines to increase the meaning of certain words in a search.
Almost all search engines ignore words from this list if they do not appear in the visible part of the page. The recommended number of words in this tag is 5-10. In addition, it was experimentally found that the breakdown of this tag into several lines affects the assessment by search engines of the relevance of the page to the query.
Previously, this tag played an important role in ranking the site, but today search engines are very critical of it. Since the developers of search engines reveal only a part of the features of page ranking algorithms, it is difficult to say how significant the content of this tag is, but the fact that a correctly filled tag will help to slightly increase the significance of these words is confirmed by representatives of all large search engines, not forgetting to indicate this in the directories for webmasters.
< meta name = "keywords" content = "Wikipedia, Meta tag, article" />
Resource-type
Describes the property or state of the page. If the tag value differs from “Document”, then search engines do not index it or may use special indexing algorithms. The meta tag is designed to scale document (used by default), rating , version , operator , formatter , creation and others. It has narrow application, in order to avoid misunderstandings, I recommend not to use it without proper understanding.
< meta name = "resource-type" content = "document" />
Revisit
The tag allows you to inform search robots about the desired term for reindexing a document in a search engine. Absolutely all search engines record its value, but absolutely all are not particularly keen to fulfill the wishes of an unknown page author. Today it is completely useless - the real frequency of updating the data on the site and its popularity has a much greater influence on the behavior of robots. That is, the dynamic pages of a popular site robots “tapping” much more often than rarely changed lone blogs, no matter what numbers are indicated using this meta. [3] .
< meta name = "revisit" content = "14" />
Robots
The tag generates information about hypertext documents that goes to search engine robots. Tag values can be the following: Index (the page must be indexed), Noindex (the document is not indexed), Follow (hyperlinks on the page are tracked), Nofollow (hyperlinks are not traced), All (includes index and follow values, enabled by default), None (includes noindex and nofollow values). First proposed by the Google search engine, but very quickly began to be taken into account by other major search engines. Proper application has a very positive effect on indexing and ranking by all major search engines, as application errors can be very harmful.
Example 1. Allow indexing of a page and use of links placed on it for subsequent indexing.
< meta name = "robots" content = "index, follow" />
or equivalent
< meta name = "robots" content = "all" />
Example 2. To prohibit indexing a page, to allow the use of links placed on it for subsequent indexing.
< meta name = "robots" content = "noindex, follow" />
Example 3. Allow indexing of a page, prohibit the use of links located on it for subsequent indexing.
< meta name = "robots" content = "index, nofollow" />
Example 4. To prohibit indexing a page and using links located on it for subsequent indexing.
< meta name = "robots" content = "noindex, nofollow" />
or equivalent
< meta name = "robots" content = "none" >
Subject
Defines the subject of the document. Almost useless due to the lack of a clear and consistent classification of topics in various search engines. It was first introduced by Yahoo in the mid-90s, but by the end of the 90s it became clear its insolvency, since no regulations were established, nor the slightest control over the use.
url
The tag stops indexing the page by the search engine, and redirects the search engine robot to the specified link. The tag is used to cancel the indexing of the "mirror" and generated pages.
< meta name = "url" content = "http://ru.wikipedia.org/" />
ViewPort [4] [5]
Data for adjusting the viewing area. Actively supported by Google and Yandex to assess the readiness of the design for display on mobile devices, as well as all modern browsers, including for mobile platforms.
< meta name = "viewport" content = "width = device-width, height = device-height, initial-scale = 1.0, maximum-scale = 1.0" >
HTTP-EQUIV
When it is not possible to modify HTTP headers on the server side, it is possible to specify them directly in the body of the page using META HTTP-Equiv . The content of the tag is compiled according to the rules for HTTP headers with the only difference being that the name of the header (the left part to the colon) is entered in the value of the http-equiv attribute, and its value in the value of the content attribute. Read more about HTTP headers on the Mozilla Developer Network website in the HTTP Headers section.
Cache-Control [6]
Caching management. It should give clear instructions to the browser and intermediate servers how to cache this page.
Possible values:
| public | the document is cached in all available caches |
|---|---|
| no-store | can be cached but not archived |
| max-age = time, must-revalidate | tells the browser how many seconds to keep the document in the cache |
| private | cached by the browser, not cached by the proxy server |
| no-cache | prohibition on caching (the browser and proxy server do not cache the document) |
| max-age = time, proxy-revalidate | indicates how many seconds to store the document in cache to the proxy server |
A complete list of possible values on the MDN website.
<! - for dynamic pages such as search results ->
< meta http-equiv = "Cache-Control" content = "no-cache, no-store, must-revalidate" >
<! - for public pages such as blog articles ->
< meta http-equiv = "Cache-Control" content = "public, max-age = 31536000" >
Content-Language
The tag allows you to specify the main language for the entire document. Widely used by browsers, search engines, aloud reading systems, text analysis systems and automatic translation. It is important for the correct choice of algorithms for automatically determining encodings for any language, including English. A common mistake when creating a new page from a template where one language is installed by default (most often English), the encoding choice for another is set can lead to low ranking in search engines, to false positives of automatic translation systems built into modern browsers and many other minor inconveniences . It becomes most significant when using Unicode encodings, in particular the most used UTF-8
< meta http-equiv = "content-language" content = "en" />
In HTML5, language specification is simplified:
< html lang = "ru" >
Content-Style-Type
Remapping the default style sheet language inside the <STYLE> and <LINK rel="stylesheet"> tags from text/css to another. It makes sense when using a default type other than text/css , for example, when using the loaded LESS or Stylus preprocessors. Used by both browsers and loadable components.
< meta http-equiv = "Content-Style-Type" content = "text / stylus-lang" >
<! - or ->
< meta http-equiv = "Content-Style-Type" content = "text / less" >
Content-Type [7]
Indicates the MIME type of the document, the code table, and possibly other technical parameters of the text.
< meta http-equiv = "Content-Type" content = "text / html; charset = UTF-8" >
In HTML5, encoding is simplified:
< meta charset = "UTF-8" >
Expires
Expires - Provides information for managing caching. If the date in the Expires header Expires not yet arrived, the browser may display a cached copy of the page. If the specified date is in the past, then the browser should, although not required, download the page from the server. If you initially indicate the past date, then the document may not be cached, that is, in theory this should provoke the browser to contact the server for a more recent version.
Some search engines may refuse to index a document with an outdated date.
Date must be specified in [RFC850].
Example:
< meta http-equiv = "Expires" content = "Wed, 26 Feb 1999 08:21:57 GMT" >
PICS-Label [8] [9] [10]
PICS — (от англ. Platform-Independent Content rating Scheme Label ) — указывает стандартизированную метку, характеризующую содержимое сайта. Сходно по назначению прокатным категориям для фильмов в кинотеатре или телевизионных передач. Используется поисковиками для ранжирования и браузерами в системах ограничения доступа. Например, если в браузере на компьютере включен родительский контроль, то браузер отклонит показ страниц с недопустимым содержимым.
Придумана давно, но активно развивается в наши дни. В некоторых, «не наших», странах обязательное использование этого тега предписывается законами для всех поголовно, в «несколько других» — этот тег обязателен для страниц с «особым» содержимым: секс, насилие и т. п., доступ к которым имеет возрастные или другие ограничения.
<!-- Безопасно для детей -->
< meta http-equiv = "PICS-Label" content = '(PICS-1.1 "http://www.weburbia.com/safe/ratings.htm" LR (s 0))' >
Маркировка должна осуществляться специальными службами — labeling services .
Здесь возможны варианты:
- Специалисты labeling service осуществляют «оценку» содержания сайта и заносят её в свою базу данных, интегрированную с web-сервером и назначают разработчику содержимое тега для указания на страницах сайта;
- Разработчик сайта заполняет для labeling services специальную форму и тем самым генерирует соответствующий тэг
<META HTTP-EQUIV="PICS-Label"...>. Такая возможность бесплатно предоставляется, например, на сервере Vancouver-Webpages .
То есть просто вписать тег в свою страницу по своему усмотрению — чревато, как минимум, непониманием, а в большинстве случаев — непредсказуемым набором неприятностей, ненужных волнений и трат.
Pragma [11]
Контроль кэширования на страницах создаваемых динамически, например, результаты поиска. Жутко устаревший, используется для совместимости со старым оборудованием и ПО, работающих с использованием протокола HTTP/1.0. До сих пор включают на тот самый «всякий» случай, что где-то, на промежуточных маршрутизаторах или прокси серверах, есть древнее ПО или оборудование. В современных условиях при использовании шифрованных соединений SSL/TLS теряет всякий смысл. Также практически бесполезен в теле страницы для промежуточных устройств.
Почти то же самое, что и HTTP заголовок Cache-Control: no-cache или <meta http-equiv="Cache-Control" content="no-cache"/> .
< meta http-equiv = "Pragma" content = "no-cache" >
Refresh
Указание браузеру автоматически перейти на другой адрес через указанное количество секунд. Если параметр url не указан, обновить страницу без использования кэша. Из-за массовых злоупотреблений с целью перевода пользователей на незатребованный ресурс, откровенного мошеннечества и использования этой особенности при распространении вредоносного ПО, практически все современные браузеры по умолчанию игнорируют инструкцию указанную в теле страницы. В современных браузерах, в том числе мобильных, имеются более технологичные средства для обновления данных на странице: AJAX , Push уведомления , WebSockets , Web Workers , ….
На сегодня — малоприменим, практически бессмысленный и затратный, как для клиента, так для сервера.
< meta http-equiv = "refresh" content = "5; url=http://www.example.com/" />
<!-- После url= кавычек нет! -->
Set-Cookie
Установка cookie в браузере . Позволяет инициализировать куки на сайтах из статичных страниц и без использования Javascript . В современных браузерах может игнорироваться в зависимости от региональных настроек в связи с законодательной политикой в некоторых странах. То есть в некоторых «не наших» странах заголовок полученный от сервера в HTTP ответе обработан будет, а указанный в теге — нет.
Формат:
< meta http-equiv = "Set-Cookie" content = "NAME=value; EXPIRES=date; DOMAIN=domain_name; PATH=path; SECURE" />
Атрибуты EXPIRES , DOMAIN , PATH и SECURE при необходимости можно опустить:
< meta http-equiv = "Set-Cookie" content = "NAME=value; />
Такой куки будет доступен для текущего домена и будет удален при закрытии браузера, или сессии, если закрывается режим «инкогнито»
Параметры
| NAME | имя cookie, не может содержать символы перевода строки, пробелов, точки с запятой (;) и табуляции |
|---|---|
| EXPIRES | время хранения cookie. После указанной даты (в формате «Wdy, DD-Mon-YYYY HH:MM:SS GMT») истекает время хранения cookie. если этот атрибут не указан, то cookie хранится в течение одного сеанса, до закрытия броузера |
| DOMAIN | домен, для которого задается значение cookie. Для доменов COM, EDU, NET, ORG, GOV, MIL, INT значение можно задавать сокращенно "", оно будет распространяться и на домен «WWW.MY.COM». Для всех остальных (в том числе и RU) значение надо задавать полностью «WWW.MY.RU». Если этот атрибут опущен, то по умолчанию используется сервера, с которого было выставлено значение cookie |
| PATH | устанавливает подмножество документов, на которые распространяется действие cookie. При значение «/doc» действие cookie будет распространено на все файлы и подкаталоги этого каталога, начинающиеся на «doc» (/doc/, /document/, /doc2/, docs.html, doc-test.htm). Если этот атрибут опущен, то значение cookie распространяется только на документы каталога, в котором расположен текущий документ |
| SECURE | указывает, что информация о cookie должна пересылаться через HTTPS (HTTP с использованием). В противном случае информация о cookie будет пересылаться по протоколу HTTP |
Перед запросом к серверу, браузер проверяет cookie. И если атрибуты NAME, DOMAIN и PATH совпадают, броузер посылает cookie серверу. Если cookie принимает новое значение, старое значение удаляется. Броузер имеет ряд ограничений по работе с cookie:
- Единовременно может храниться не более 300 значений cookie.
- не может превышать 4 Кбайт.
- От одного сервера (домена) не может быть более 20 cookie.
Эти ограничения могут быть несколько иными, в зависимости от настройки и типа броузера. Если происходит превышение лимита (общего или по домену) удаляется первая по времени запись. Удаление происходит, не зависимо от значения атрибута EXPIRES. При превышении 4 Кбайт, cookie усекается.
< meta http-equiv = "Set-Cookie" content = "NAME=cookexample; EXPIRES=Fri Jun 30 2017 15:32:49 GMT+0800; DOMAIN=WWW.MY.RU; PATH=/; SECURE" />
< meta http-equiv = "Set-Cookie" content = "NAME=cookexample;" />
Window-target
Назначает окно текущей страницы. Действие аналогично атрибуту target HTML тега A , только не для вновь открываемой, а именно для данной страницы.
| _blank | документ откроется в новой вкладке/окне |
|---|---|
| _parent | страница откроется в родительском фрейме текущей вкладки по отношению к текущему фрейму из которого была вызвана страница; если текущий фрейм является верхним, то в данном случае поведение равнозначно _self и _top |
| _top | загрузка в самый верхний фрейм текущей вкладки |
| _self | открытие документа во фрейме из которого была вызвана загрузка страницы |
| <name> | имя окна (вкладки или фрейма); если ранее загружалась страница с установленным таким именем в метатеге `window-target` или была открыта по ссылке с указанным именем в атрибуте target , то страница должна загрузиться в той же вкладке; если этот мета поддерживается браузером, то позволяет все страницы определённой тематики (например, справка по использованию сайта или контактные данные) открывать в ту же вкладку, не создавая новую |
Принудительно открыть эту страницу во фрейме верхнего уровня текущей вкладки:
< meta http-equiv = "Window-target" content = "_top" >
Открыть страницу в новой вкладке, либо во вкладке с именем «my_site_documentation». Все страницы с таким тегом и точно таким именем (в некоторых браузер важен регистр символов в имени) будут открываться в одной и той же вкладке.
< meta http-equiv = "Window-target" content = "my_site_documentation" >
Не все браузеры распознают и одинаково обрабатывают этот мета.
Imagetoolbar [12]
Управлял(ет?) Image Toolbar в Internet Explorer 6.0.
- image toolbar был разработан только для IE версии 6. В более поздних версиях он отсутствует
- существует плагин для Mozilla Firefox , который воссоздает такой же image bar. Плагин реагирует на метатег imagetoolbar и атрибут galleryimg аналогично IE6
< meta http-equiv = "imagetoolbar" content = "no" />
ClearType
Для Mobile Internet Explorer — позволяет принудительно активировать технологию ClearType сглаживания шрифтов на LCD экранах.
Технология ClearType — проприетарная, то есть исключительное право на её применение принадлежит Microsoft, используется в системах семейства Windows. Обращали внимание, что в IE те же шрифты выглядят иначе, чем в других браузерах? А в Photoshop? Это в основном из-за разных технологий сглаживания шрифтов.
Возможно, понимается и другими браузерами от Microsoft, однако на «старших» системах эта технология включена по умолчанию и при некоторых настройках отключается при работе от батерии. А так как «серфить» на ноутбуке с батареи и в MS Explorer, это ещё нужно догадаться либо попасть в экстремальную ситуацию, когда не до таких мелочей, то мало кто обращал внимание — работает ли это принудительное включение на десктопных IE. А если и обращали, то «почему-то» не сочли нужным об этом где-нибудь оставить информацию.
< meta http-equiv = "cleartype" content = "on" />
X-UA-Compatible [13]
Исключительно для браузеров от Microsoft : Iternet Explorer версий с 8 по 11 и Edge . Впервые стал распознаваться браузером IE8, когда в комплект поставки были включены все версии движка, начиная с 5. В различных релизах IE поставлялись разные наборы доступных движков. Этот метатег диктует браузерам этого славного семейства какую версию движка использовать для отображения страницы. Браузеры Edge сегодня не имеют возможности переключаться в режимы Internet Explorer, лишь эмулируют их поведение, равно как и IE воспринимает указание на Edge, как приказ использовать новейший из имеющихся в наличии движок.
< meta http-equiv = "X-UA-Compatible" content = "IE=edge" >
Значение метатегов
Метаданные о веб-странице изначально предназначались в том числе для того, чтобы помочь поисковым машинам отнести веб-страницу к той или иной категории. В 90-е годы метатеги активно использовались в целях раскрутки своего сайта, в том числе предоставляя ложные или избыточные данные. За последние десятилетия разработчиками поисковых систем было предпринято множество мер по пресечению таких манипуляций: например, из факторов безусловного ранжирования был исключён тег keywords , принципы правильного заполнения основных тегов TITLE и description также поменялись.
В связи с тем, что метатеги несут чисто служебную функцию, и, кроме того, значительно увеличивают размер гипертекстового документа, начинающие Web-разработчики зачастую игнорируют их либо используют шаблонные значения предоставляемые инструментами разработки. Однако, грамотное предоставление служебной информации, которую одинаково легко могут обработать и браузеры, и поисковые ситстемы, и стороннее ПО, помогает успешней индексировать страницы в поисковых системах и тоньше управлять поведением браузеров.
See also
- Поисковая оптимизация
- HTML , XHTML
- Метаданные
- Веб-страница
- nofollow , noindex
- Браузер
Notes
- ↑ 1 2 3 HTML5 Transport Protocol on Vimeo
- ↑ 1 2 HTML META Tags
- ↑ Яндекс о Revisit-After
- ↑ Настройте область просмотра | PageSpeed Insights . Google Developers. Дата обращения 30 июня 2017.
- ↑ Using the viewport meta tag to control layout on mobile browsers (англ.) . Mozilla Developer Network. Дата обращения 30 июня 2017.
- ↑ Cache-Control (англ.) . Mozilla Developer Network. Дата обращения 30 июня 2017.
- ↑ <meta charset="utf-8"> vs <meta http-equiv="Content-Type"> . stackoverflow.com. Дата обращения 30 июня 2017.
- ↑ Метатег PICS-Label . xiper.net. Дата обращения 30 июня 2017.
- ↑ XX - XX xxxxxxx xxx xx XX, xx (англ.) (недоступная ссылка) . www.weburbia.com. Дата обращения 30 июня 2017. Архивировано 14 января 2013 года.
- ↑ Platform for Internet Content Selection (PICS)Platform for Internet Content Selection (PICS) (англ.) . www.w3.org. Дата обращения 30 июня 2017.
- ↑ Pragma (англ.) . Mozilla Developer Network. Дата обращения 30 июня 2017.
- ↑ Метатег imagetoolbar . xiper.net. Дата обращения 30 июня 2017.
- ↑ What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do? . stackoverflow.com. Дата обращения 30 июня 2017.