About
The link 1) 2) represents metadata that expresses inter-document relationships.
It's not an hyperlink
Syntax
The link element can be used only within the head element.
<head>
<link
rel="stylesheet"
media="screen,projection"
href="css/common.min.css"
integrity="sha384-ZYfZnVukOuh/gRpU9uN+T9XwwRFJ9Y+0Ylk3zKvI184omb/HoOtQ0F8Iol7Nix7q">
....
</head>
where:
- media is a list of media query separated by a comma.
- href is the path to the resource (here a style sheet)
- crossorigin to set the CORS policy. See What is the HTML crossorigin attribute ? (CORS policy)
- integrity is a hash of the file to control that the content is genuine. See HTML - Integrity attribute (SRI | Source Resource Integrity)
You can also add a css file through the CSS Import rule
Rel
The value of the rel attribute define the type of document (ie the type of relation, ie the type of resource).
- stylesheet: stylesheet
- preload: preload
- pingback: pingback
- canonical: canonical
- …
Stylesheet
The stylesheet value loads a style sheet 3)
- Sync version:
<link href="style.css" rel="stylesheet">
- Async version with preload
<!-- In the header -->
<link href="style.css" rel="preload" as="style">
<!-- Where you want to use the stylesheet (it can be at the bottom of the body) -->
<link href="style.css" rel="stylesheet" >
Canonical
A canonical value should be the unique identifier of a document for this entire life. See HTML - Canonical URL
<link rel="canonical" href="https://gerardnico.com/cat/post1" />
Preload
preload permits to preload a resource that will be used later. How to preload HTML resource (Javascript, StyleSheet)
Example with a video:
<link rel="preload" href="sintel-short.mp4" as="video" type="video/mp4">
Pingback
pingback permits to advertise the pingback endpoint.
<link rel="pingback" href="https://websiteA.com/xmlrpc">
How to add a link element dynamically ?
Example with one or more stylesheet
const head = document.querySelector('head');
const stylesheets = [
["https://cdnjs.cloudflare.com/ajax/plugins/toolbar/prism-toolbar.css","sha256-kK4/JIYJUKI4Zdg9ZQ7FYyRIqeWPfYKi5QZHO2n/lJI="],
["https://cdn.example.com/stylesheet","integrityHash"],
];
stylesheets.forEach(stylesheet => {
let link = document.createElement('link');
link.rel="stylesheet"
link.href=stylesheet[0];
link.integrity=stylesheet[1];
link.crossOrigin="anonymous";
head.append(link);
}
)