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:
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}');
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}");
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!