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.Das obige ist der detaillierte Inhalt vonWie fügt man ein Stylesheet mit JavaScript aus dem Body in den Kopf ein?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!