Home  >  Article  >  Web Front-end  >  How Can I Add Stylesheets Dynamically to the Head Using JavaScript?

How Can I Add Stylesheets Dynamically to the Head Using JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-15 13:49:03987browse

How Can I Add Stylesheets Dynamically to the Head Using JavaScript?

Adding Stylesheets Dynamically to the Head Using JavaScript

Many Content Management Systems (CMSs) restrict access to the head section, making it challenging to incorporate additional stylesheets. However, a clever solution using JavaScript can effectively tackle this issue.

To inject stylesheets into the head section after the tag, we can leverage JavaScript's ability to manipulate the Document Object Model (DOM). The following code snippet demonstrates this technique:

function addCss(fileName) {
  var head = document.head;
  var link = document.createElement("link");

  link.type = "text/css";
  link.rel = "stylesheet";
  link.href = fileName;

  head.appendChild(link);
}

For a simpler solution using jQuery, consider the following:

function addCss(fileName) {
  var link = $("<link />", {
    rel: "stylesheet",
    type: "text/css",
    href: fileName
  });
  $('head').append(link);
}

Note: Recent specifications prohibit the use of the element in the tag. However, most browsers still render it correctly. Therefore, adding the stylesheet to the tag is technically feasible, although adhering to specifications dictates placing it in the tag instead.

The above is the detailed content of How Can I Add Stylesheets Dynamically to the Head Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn