Home > Web Front-end > CSS Tutorial > How to Inject Stylesheets into the Head of Your Document with JavaScript?

How to Inject Stylesheets into the Head of Your Document with JavaScript?

Barbara Streisand
Release: 2024-11-19 05:37:02
Original
813 people have browsed it

How to Inject Stylesheets into the Head of Your Document with JavaScript?

Injecting Stylesheets into the Head with JavaScript

Your inability to modify the head section of your CMS poses a challenge when adding CSS stylesheets to your website. However, a solution exists by utilizing JavaScript to dynamically inject stylesheets into the page.

To achieve this, you can create a script and place it just before the closing tag. Within this script, you can construct a link element using the document.createElement() method and set its type to "text/css" and rel to "stylesheet." Finally, set the href attribute to the desired stylesheet file.

Here's an example using vanilla JavaScript:

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);
}

addCss('{my-url}');
Copy after login

Alternatively, if you prefer jQuery for ease of use:

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

addCss("{my-url}");
Copy after login

While it was previously suggested to append the link element to the body, this approach may result in incorrect rendering of the stylesheet in some browsers. Therefore, it is recommended to insert the link directly into the head of the document as shown in the provided examples.

The above is the detailed content of How to Inject Stylesheets into the Head of Your Document with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template