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