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.
Load CSS and JS files dynamically: We create a script element for the JS file and link element for the CSS file as required using DOM, assign the appropriate attributes to them, and then add the element to the desired location within the document tree using the element. append() method.
To link a CSS file with your HTML file, you have to write the next script on your HTML file inside the head tag. To link a Js file with your HTML, you only have to add the source of the script inside the body tag or outside; it doesn't matter.
Yes, it is possible to use JS in CSS :) Houdini enables faster parse times than using JavaScript HTMLElement. style for style changes. Browsers parse the CSSOM — including layout, paint, and composite processes — before applying any style updates found in scripts.
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);
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With