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

Tags: , , ,

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% }"

Or something of that nature.


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

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; }";

Source: stackoverflow