HTML Tutorial - HTML Resource link








The link element creates a relationship between an HTML document and an external resource, a CSS stylesheet or a Javascript file.

link element has local Attributes: href, rel, hreflang, media, type, sizes.

  • href - Specifies the URL of the resource that the link element refers to.
  • hreflang - Specifies the language of the linked resource.
  • media - Specifies the device that the linked content is intended for.
  • rel - Specifies the kind of relationship between the document and the linked resource.
  • sizes - Specifies the size of icons.
  • type - Specifies the MIME type of the linked resource, such as text/css or image/x-icon.

The sizes attribute has been added in HTML5 and the attributes charset, rev and target are obsolete in HTML5.

The rel attribute value determines how the browser deals with the link element. The following list shows common values for the rel attribute.

  • alternate - Links to an alternative version of the document, such as a translation to another language.
  • author - Links to the author of the document.
  • help - Links to help related to the current document.
  • icon - Specifies an icon resource.
  • license - Links to a license associated with the current document.
  • pingback - Specifies a pingback server, which allows a blog to be notified automatically when other web sites link to it.
  • prefetch - Preemptively fetches a resource.
  • sylesheet - Loads an external CSS stylesheet.




Example

To demonstrate the link element, I have created a stylesheet called styles.css, which has the following content.

a  {
    background-color: grey;
    color: red;
    padding: 0.5em;
}

To apply this stylesheet, we can use the link element as shown in the following code.

<!DOCTYPE HTML>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
  <p>This is a test.</p>
  <a href="http://java2s.com">Visit java2s.com</a>
</body>
</html>

You can use multiple link elements to load multiple external resources. An external stylesheet can be reused in multiple documents.





Prefetch a Resource

You can ask the browser to pre-fetch a resource.

The following code shows the use of the link element to specify prefetching.

<!DOCTYPE HTML>
<html>
<head>
<link rel="prefetch" href="/page2.html" />
</head>
<body>
  <p>This is a test.</p>
  <a href="http://java2s.com">Visit java2s.com</a>
  <a href="page2.html">Page 2</a>
</body>
</html>

The code above set the rel attribute to prefetch and specified that an HTML page, page2.html, be loaded in the expectation that the user will use this page.