Using createTextNode
to set the content of a <style>
element is generally considered a safer practice compared to using innerHTML
. Using createTextNode
ensures that the content is treated as pure text and not parsed as HTML. This can prevent potential cross-site scripting (XSS) attacks if the CSS content were to somehow include malicious code.
Also, using the createTextNode
approach is a more standards-compliant way to insert text content into the DOM. It ensures that the content is treated exactly as text, without any ambiguity. While the performance difference is usually negligible, createTextNode
can sometimes be more efficient as it doesn't involve the HTML parser.
But in tightly controlled cases, innerHTML
is fine. Here's an example of injection from a URL:
function injectCSS(url: string, id: string) {
if (document.getElementById(id)) return; // Check if the stylesheet is already injected
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = url;
link.id = id; // Assign an ID to the link element
document.head.appendChild(link);
}
function removeCSS(id: string) {
const link = document.getElementById(id);
if (link) {
link.parentNode?.removeChild(link); // Remove the link element by its ID
}
}
const cssID = "my-stylesheet";
const cssPath = "path/to/your.css";
injectCSS(cssPath, cssID); // Inject the CSS
removeCSS(cssID); // Remove the CSS when needed
Or from a string, by creating a new <script>
element and appending a TextNode
containing the CSS file:
injectCSS("body {filter: blur(5px);}", cssID);
function injectCSS(cssContent: string, id: string) {
if (document.getElementById(id)) return; // Check if the stylesheet is already injected
const style = document.createElement("style");
style.id = id; // Assign an ID to the style element
style.type = "text/css";
style.appendChild(document.createTextNode(cssContent));
document.head.appendChild(style);
}