Home > Web Front-end > CSS Tutorial > How to Inject a Stylesheet into the Head with JavaScript from the Body?

How to Inject a Stylesheet into the Head with JavaScript from the Body?

Barbara Streisand
Release: 2024-11-14 19:34:02
Original
648 people have browsed it

How to Inject a Stylesheet into the Head with JavaScript from the Body?

Injecting Stylesheet into Head with JavaScript in Body

The inability to edit the section of a CMS can pose a challenge when needing to add a CSS stylesheet to a website. This issue can be resolved by utilizing JavaScript to inject the stylesheet directly into the section, even if the script itself is appended to the end of the tag.

To achieve this, a new element is created dynamically using JavaScript. This element is configured with the appropriate attributes:

  • type: "text/css"
  • rel: "stylesheet"
  • href: The URL of the stylesheet to be loaded

Once created, the element is appended to the section using the appendChild() method on the Document.head object.

Example:

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

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

  head.appendChild(link);
}

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

This code creates a new element with the specified href and appends it to the section.

Using jQuery:

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

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

Note: While it is technically possible to append the element to the section, it is not recommended as it violates the HTML specification. Therefore, it is preferable to append the element to the section for compliance and potential future browser compatibility issues.

The above is the detailed content of How to Inject a Stylesheet into the Head with JavaScript from the Body?. 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