0

I am trying to load css from javascript. I have a little icon I need styles for that my users display on their site through my script tag like <script src="mywebiste.com/api.js"></script

Rather than doing inline styles like this:

document.body.innerHTML +=
'<div style="position:absolute;width:10%;height:10%;opacity:0.3;
             z-index:100;background:#000;">
</div>';

How can I load css styles from javascript? How do widgets like intercom.com do it?

2 Answers2

0

Assuming you already have the div inside body, You can use jQuery css()

$("body > div").css({
  "position": "absolute",
   "width": "10%",
   "height": "10%",
   "opacity" : "0.3",
   "z-index":"100",
   "background":"#000"
});
Dan Philip Bejoy
  • 4,321
  • 1
  • 18
  • 33
0
<script type="text/javascript">
var link = document.createElement("link");
link.href = "path-to-your-css-file";
link.type = "text/css";
link.rel = "stylesheet";
link.media = "screen,print";

document.getElementsByTagName("head")[0].appendChild(link);
</script>

Create the <link> element in javascript with var link = document.createElement("link");

Then add the necessary html attributes.

Finally append it to the <head> section:

document.getElementsByTagName("head")[0].appendChild(link);

Ryan Tuosto
  • 1,941
  • 15
  • 23