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 exam
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);
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>```
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);
}