Is there a way to load css and javascript from a string?

I saw many examples of loading CSS and javascript dynamically from a file. Here is 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 like that.

+3
source share
1 answer
var javascript = "alert('hello');";
eval(javascript);

This will load JavaScript from the line, but will be warned that it is extremely unsafe and not recommended. If a malicious process has ever interrupted your JavaScript string, this can lead to security problems.

As for CSS, you can add a style tag to the page using jQuery, for example:

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

Or, for JavaScript purists:

var s = document.createElement("style");
s.innerHTML = "body { background-color:white !important; }";
document.getElementsByTagName("head")[0].appendChild(s);
+11
source

All Articles