5

I've seen many examples of loading CSS and javascript dynamically from a file. Here's a good example. But is there a way to load CSS or javascript as a string? For example, something like:

var style = ".class { width:100% }"
document.loadStyle(style);

Or something of that nature.

3 Answers 3

14
var javascript = "alert('hello');";
eval(javascript);

This will load the JavaScript from a string, but be warned that this is highly insecure and not recommended. If a malicious process ever interfered with your string of JavaScript, it could result in security issues.

As far as CSS goes, you can append a style tag to the page using jQuery, like so:

$('head').append("<style>body { background-color: grey; }</style>");

Or, for the JavaScript purists:

var s = document.createElement("style");
s.innerHTML = "body { background-color:white !important; }";
document.getElementsByTagName("head")[0].appendChild(s);
Sign up to request clarification or add additional context in comments.

1 Comment

4

Another way without using potentially dangerous eval and innerHTML is creating a link element with base64 encoded URL:

function loadCSS(cssStyles) {
  const link = document.createElement('link');
  link.href = `data:text/css;base64,${btoa(cssStyles)}`;
  link.type = 'text/css';
  link.rel = 'stylesheet';
  document.getElementsByTagName('head')[0].appendChild(link);
}

Comments

0

but, this code work on only single HTML file that contain style tag

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style></style>
</head>
<body>
    <div class="foo"></div>
    <div class="bar"></div>
</body>
<script>
    const cssText = `.foo{
            background-color: black;
            width: 100px;
            height: 100px;
        }
        .bar{
            background-color: gray;
            width: 100px;
            height: 100px;
        }`
    document.querySelector("style").innerText = cssText;
</script>
</html>```

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.