--- title: ': The External Resource Link element' slug: Web/HTML/Element/link translation_of: Web/HTML/Element/link original_slug: Web/HTML/Елемент/link ---
{{HTMLRef}}

Елемент посилання зовнішнього ресурсу HTML ( <link>) визначає відносини між поточним документом і зовнішнім ресурсом. Цей елемент найчастіше використовується для посилання на {{Glossary ("CSS", "stylesheets")}}, але також використовується для встановлення значків сайтів (іконок стилів favicon і мобільного домашнього екрана / значків програм) .

{{EmbedInteractiveExample ("сторінки / вкладки / link.html")}}

Щоб пов’язати зовнішню таблицю стилів, потрібно включити <link>елемент у {{HTMLElement ("head")}} так:

<link href = "main.css" rel = "stylesheet">

Цей простий приклад надає шлях до таблиці стилів всередині hrefатрибута і relатрибут зі значенням stylesheet. Поняття rel"відносини", і, можливо, одна з ключових особливостей <link>елемента - значення позначає, як пов'язаний елемент пов'язаний з документом, що містить. Як видно з посилання на типи посилань, існує багато різних типів відносин.

Існує ряд інших поширених типів. Наприклад, посилання на значок сайту:

<link rel = "icon" href = "favicon.ico">

Існує ряд інших relзначень значків , які в основному використовуються для позначення спеціальних типів піктограм для використання на різних мобільних платформах, наприклад:

<link rel = "розмір яблуко-значка-попередній" розмір = "114x114"
      href = "apple-icon-114.png" type = "image / png">

sizesАтрибут вказує розмір значків, в той час як typeмістить MIME - тип ресурсу пов'язані між собою . Вони надають корисні поради, які дозволяють браузеру вибрати найбільш доступну піктограму.

Ви також можете вказати тип або запит носія в mediaатрибуті; цей ресурс буде завантажено лише в тому випадку, якщо умова носія є істинною. Наприклад:

<link href = "print.css" rel = "stylesheet" media = "print">
<link href = "mobile.css" rel = "stylesheet" media = "екран і (max-width: 600px)

До <link>елемента також додано кілька цікавих нових функцій продуктивності та безпеки . Візьміть цей приклад:

<link rel = "preload" href = "myFont.woff2" як = "шрифт"
      type = "font / woff2" crossorigin = "anonymous">

relЗначення preloadвказує на те, що браузер повинен попередньо завантажити цей ресурс (див предзагрузкі зміст з отн = "переднавантаження» для отримання більш докладної інформації), з asатрибутом , що вказує певний клас контенту, витягується. crossoriginАтрибут вказує , чи повинен ресурс бути залучена з {{Glossary("CORS")}} запитом.

Інші примітки щодо використання:

Атрибути

Цей елемент включає глобальні атрибути .

{{HTMLAttrDef ("as")}}
Цей атрибут використовується тільки тоді, коли rel="preload"або rel="prefetch"було встановлено на <link>елементі. Вона визначає тип завантажуваного контенту <link>, який необхідний для визначення пріоритетів вмісту, відповідності запиту, застосування правильної політики безпеки контенту та встановлення правильного заголовка запиту {{HTTPHeader ("Accept")}}.
{{HTMLAttrDef ("crossorigin")}}
Цей перерахований атрибут вказує, чи слід використовувати {{Glossary("CORS")}} при отриманні ресурсу. Зображення з підтримкою CORS можна повторно використовувати в елементі {{HTMLElement ("canvas")}}, не засмучуючись . Дозволені значення:
anonymous
Запит на перехресне походження (тобто з HTTP-заголовком {{HTTPHeader ("Походження")}} виконується, але не надсилаються дані облікового запису (тобто, файли cookie, сертифікат X.509 або HTTP Basic). Якщо сервер не надає облікових даних сайту (не встановлюючи заголовок HTTPHeader ("Access-Control-Allow-Origin")}} HTTPHeader, зображення буде заплямовано, а його використання обмежене.
use-credentials
Запит на перехресне походження (тобто з Originзаголовком HTTP) виконується разом із відправленими обліковими даними (тобто виконується cookie, сертифікат та / або HTTP Basic аутентифікація). Якщо сервер не надає облікових даних сайту (через {{HTTPHeader ("Access-Control-Allow-Credentials")}} HTTP-заголовок), ресурс буде заплямовано і його використання буде обмежене.
Якщо атрибут відсутній, ресурс вибирається без запиту {{Glossary ("CORS")}} (тобто без відправлення Originзаголовка HTTP), що запобігає його непрямому використанню. Якщо він недійсний, він обробляється так, якби було використано анонімне перераховане ключове слово . Див настройки CORS атрибути для отримання додаткової інформації.
{{HTMLAttrDef ("href")}}
Цей атрибут визначає {{глосарій ("URL")}} пов'язаного ресурсу. URL-адреса може бути абсолютною або відносною.
{{HTMLAttrDef ("hreflang")}}
Цей атрибут вказує мову пов'язаного ресурсу. Це суто консультативний характер. Дозволені значення визначаються BCP47 . Використовуйте цей атрибут, лише якщо присутній атрибут {{HTMLAttrxRef ("href", "a")}}.
{{HTMLAttrDef ("значення")}} {{Experimental_Inline}}
Вказує відносну важливість ресурсу. Підказки щодо пріоритетів делегуються за допомогою значень:

auto: Вказує на  відсутність уподобань . Для визначення пріоритету ресурсу браузер може використовувати власну евристику.

high: Вказує браузеру, що ресурс має  високий пріоритет.

low: Вказує браузеру, що ресурс має  низький пріоритет.

Примітка:importance атрибут може бути використаний тільки для <link>елемента , якщо rel="preload"або rel="prefetch"присутній.

{{HTMLAttrDef ("цілісність")}} {{Experimental_Inline}}
Містить вбудовані метадані - криптографічний хеш-код, зашифрований за допомогою base64, який повідомляє веб-переглядачу. Цей веб-переглядач може використовувати це, щоб переконатися, що отриманий ресурс доставлений без несподіваних маніпуляцій. Див Subresource цілісності .
{{HTMLAttrDef ("медіа")}}
Цей атрибут визначає носій, до якого застосовується пов'язаний ресурс. Його значення має бути тип медіа / медіа-запит . Цей атрибут є в основному корисним при підключенні до зовнішніх таблиць стилів - це дозволяє користувальницькому агенту підібрати найбільш адаптований для пристрою, на якому він працює.

Примітки:

  • В HTML 4, це може бути тільки простий білий список розділених пробілами опису медіа - литералов, тобто типів і груп , в яких визначені і дозволені в якості значень для цього атрибута, наприклад print, screen, aural, braille. HTML5 розширив це до будь-яких типів медіа-запитів , які є набором допустимих значень HTML 4.
  • Браузери, які не підтримують CSS3 Media Queries , не обов'язково розпізнають адекватне посилання; не забувайте встановлювати резервні посилання, обмежений набір медіа-запитів, визначених у HTML 4.
{{HTMLAttrDef ("referrerpolicy")}} {{Experimental_Inline}}
Рядок, який вказує, який референт використовувати для отримання ресурсу:
{{HTMLAttrDef ("rel")}}
Цей атрибут іменує відношення пов'язаного документа до поточного документа. Атрибут повинен бути розділеним пробілами списком значень типів посилань .
{{HTMLAttrDef ("розміри")}}
Цей атрибут визначає розміри піктограм для візуальних медіа, що містяться в ресурсі. Він повинен бути присутнім, лише якщо {{HTMLAttrxRef ("rel", "link")}} містить значення iconабо нестандартний тип, наприклад, Apple apple-touch-icon. Він може мати такі значення:

Примітка. Більшість форматів піктограм можуть зберігати лише одну піктограму; тому більшу частину часу {{HTMLAttrxRef ("розміри")}} містить тільки один запис. Формат ICO MS, як і ICNS від Apple. ICO є більш повсюдним; Ви обов'язково повинні використовувати його.

{{HTMLAttrDef ("назва")}}
titleАтрибут має спеціальну семантику на <link>елементі. При використанні на ньому <link rel="stylesheet">він визначає бажану або альтернативну таблицю стилів . Неправильне використання може призвести до ігнорування таблиці стилів .
{{HTMLAttrDef ("type")}}
Цей атрибут використовується для визначення типу змісту, з яким пов'язаний. Значення атрибута має бути типом MIME, таким як text / html , text / css і так далі. Загальним використанням цього атрибуту є визначення типу стильової таблиці, на яку посилаються (наприклад, текст / css ), але враховуючи, що CSS є єдиною мовою таблиць стилів, що використовується в Інтернеті, не тільки можна опустити typeатрибут, але й насправді тепер рекомендується практика. Він також використовується для rel="preload"типів посилань, щоб переконатися, що браузер завантажує лише типи файлів, які він підтримує.

Нестандартні атрибути

{{HTMLAttrDef ("вимкнено")}} {{Нестандартний_Інтернет}}
This attribute is used to disable a link relationship. In conjunction with scripting, this attribute could be used to turn on and off various style sheet relationships.

Note: While there is no disabled attribute in the HTML standard, there is a disabled attribute on the HTMLLinkElement DOM object.

{{HTMLAttrDef("methods")}} {{Non-standard_Inline}}
The value of this attribute provides information about the functions that might be performed on an object. The values generally are given by the HTTP protocol when it is used, but it might (for similar reasons as for the title attribute) be useful to include advisory information in advance in the link. For example, the browser might choose a different rendering of a link as a function of the methods specified; something that is searchable might get a different icon, or an outside link might render with an indication of leaving the current site. This attribute is not well understood nor supported, even by the defining browser, Internet Explorer 4.
{{HTMLAttrDef("prefetch")}} {{Non-standard_Inline}} {{secureContext_inline}}
This attribute identifies a resource that might be required by the next navigation and that the user agent should retrieve it. This allows the user agent to respond faster when the resource is requested in the future.
{{HTMLAttrDef("target")}} {{Non-standard_Inline}}
Defines the frame or window name that has the defined linking relationship or that will show the rendering of any linked resource.

Obsolete attributes

{{HTMLAttrDef("charset")}} {{Obsolete_Inline}}
This attribute defines the character encoding of the linked resource. The value is a space- and/or comma-delimited list of character sets as defined in {{rfc(2045)}}. The default value is iso-8859-1.
Usage note: To produce the same effect as this obsolete attribute, use the {{HTTPHeader("Content-Type")}} HTTP header on the linked resource.
{{HTMLAttrDef("rev")}} {{Obsolete_Inline}}
The value of this attribute shows the relationship of the current document to the linked document, as defined by the {{HTMLAttrxRef("href", "link")}} attribute. The attribute thus defines the reverse relationship compared to the value of the rel attribute. Link type values for the attribute are similar to the possible values for {{HTMLAttrxRef("rel", "link")}}.

Note: This attribute is considered obsolete by the WHATWG HTML living standard (which is the specification MDN treats as canonical). However, it's worth noting that rev is not considered obsolete in the W3C specification. That said, given the uncertainty, relying on rev is unwise.

Instead, you should use the {{HTMLAttrxRef("rel", "link")}} attribute with the opposite link type value. For example, to establish the reverse link for made, specify author. Also this attribute doesn't stand for "revision" and must not be used with a version number, even though many sites misuse it in this way.

Styling with CSS

The <link> element has no visual presence on a web document, therefore it has no styling considerations to worry about.

Examples

Including a stylesheet

To include a stylesheet in a page, use the following syntax:

<link href="style.css" rel="stylesheet">

Providing alternative stylesheets

You can also specify alternative style sheets.

The user can choose which style sheet to use by choosing it from the View > Page Style menu. This provides a way for users to see multiple versions of a page.

<link href="default.css" rel="stylesheet" title="Default Style">
<link href="fancy.css" rel="alternate stylesheet" title="Fancy">
<link href="basic.css" rel="alternate stylesheet" title="Basic">

Providing icons for different usage contexts

You can include links to several different icons on the same page, and the browser will choose which one works best for its particular context using the rel and sizes values as hints.

<!-- third-generation iPad with high-resolution Retina display: -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="favicon144.png">
<!-- iPhone with high-resolution Retina display: -->
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="favicon114.png">
<!-- first- and second-generation iPad: -->
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="favicon72.png">
<!-- non-Retina iPhone, iPod Touch, and Android 2.1+ devices: -->
<link rel="apple-touch-icon-precomposed" href="favicon57.png">
<!-- basic favicon -->
<link rel="icon" href="favicon32.png">

Conditionally loading resources with media queries

You can provide a media type or query inside a media attribute; this resource will then only be loaded if the media condition is true. For example:

<link href="print.css" rel="stylesheet" media="print">
<link href="mobile.css" rel="stylesheet" media="all">
<link href="desktop.css" rel="stylesheet" media="screen and (min-width: 600px)">
<link href="highres.css" rel="stylesheet" media="screen and (min-resolution: 300dpi)">

Stylesheet load events

You can determine when a style sheet has been loaded by watching for a load event to fire on it; similarly, you can detect if an error has occurred while processing a style sheet by watching for an error event:

<script>
var myStylesheet = document.querySelector('#my-stylesheet');

myStylesheet.onload = function() {
  // Do something interesting; the sheet has been loaded
}

myStylesheet.onerror = function() {
  console.log("An error occurred loading the stylesheet!");
}
</script>

<link rel="stylesheet" href="mystylesheet.css" id="my-stylesheet">

Note: The load event fires once the stylesheet and all of its imported content has been loaded and parsed, and immediately before the styles start being applied to the content.

Preload examples

You can find a number of <link rel="preload"> examples in Preloading content with rel="preload".

Technical summary

Content categories Metadata content. If itemprop is present: flow content and phrasing content.
Permitted content None, it is an {{Glossary("empty element")}}.
Tag omission As it is a void element, the start tag must be present and the end tag must not be present
Permitted parents Any element that accepts metadata elements. If itemprop is present: any element that accepts phrasing content.
Permitted ARIA roles None
DOM interface {{DOMxRef("HTMLLinkElement")}}

Specifications

Specification Status Comment
{{SpecName("Preload")}} {{Spec2("Preload")}} Defines <link rel="preload">, and the as attribute.
{{SpecName("Subresource Integrity", "#HTMLLinkElement", "lt;link>")}} {{Spec2("Subresource Integrity")}} Added the integrity attribute.
{{SpecName("HTML WHATWG", "semantics.html#the-link-element", "<link>")}} {{Spec2("HTML WHATWG")}} No changes from latest snapshot
{{SpecName("HTML5 W3C", "document-metadata.html#the-link-elemen", "<link>")}} {{Spec2("HTML5 W3C")}} Added crossorigin and sizes attributes; extended values of media to any media queries; added numerous new values for rel.
{{SpecName("HTML4.01", "struct/links.html#h-12.3", "<link>")}} {{Spec2('HTML4.01')}}  
{{SpecName("Resource Hints", "#prefetch", "prefetch")}} {{Spec2("Resource Hints")}} Added dns-prefetch, preconnect, prefetch, and prerender.

Browser compatibility

{{Compat ("html.elements.link", 3)}}

Дивіться також