Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 852
sak Avatar asked May 05 '12 00:05

sak


People also ask

How do I dynamically load CSS files?

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.

How do I put HTML CSS and JavaScript in one file?

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.

Can you embed JavaScript in CSS?

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.


2 Answers

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);
like image 90
jmort253 Avatar answered Sep 26 '22 21:09

jmort253


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);
}
like image 36
icl7126 Avatar answered Sep 24 '22 21:09

icl7126