Skip to content

Instantly share code, notes, and snippets.

@rshaker
Created August 24, 2023 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rshaker/3d02cbd236576f9e0e47d260a1626bc5 to your computer and use it in GitHub Desktop.
Save rshaker/3d02cbd236576f9e0e47d260a1626bc5 to your computer and use it in GitHub Desktop.
Injecting CSS into a web page using Javascript

Injecting CSS into a web page using Javascript

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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment