Skip to content
Advertisement

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

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.

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement