2

I am trying to dynamically load CSS links in <link> tag with JavaScript.

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="#" class="js-load-css">
</head>
<body>

<h1>I am formatted with a linked style sheet</h1>
<p>Me too!</p>

</body>
</html>

Two questions here:

1) Is having empty href attribute with <link> Ok?

2) Is there any other tag that would better suite in this situation?

Shota
  • 6,910
  • 9
  • 37
  • 67

2 Answers2

0

Is having empty href attribute with Ok?

It is a relative URL that resolves to the current URL, which is an HTML document, which is not a stylesheet. So no.

Is there any other tag that would better suite in this situation?

No. Append a new <link> element to document.head when your CSS wants to load the CSS. There is no need for a placeholder element at all.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Just use Javascript to add a new stylesheet <link> tag to the document.head.

var stylesheet = document.createElement("link");
stylesheet.rel = "stylesheet";
stylesheet.type = "text/css";
stylesheet.href = "your_file.css";

document.head.appendChild(stylesheet);
robinvrd
  • 1,760
  • 12
  • 28