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?

0

2 Answers 2

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"
});
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.