0

So I built a widget that embeds into my clients website with some JS. The code that's being rendered requires some css so it looks and functions properly on the website. How should I go about including thse stylesheet and have it work with the code inside the javascript?

<div id="widget"></div>
<script type="text/javascript">
  (function() {
    var sp = document.createElement('script'); sp.type = 'text/javascript'; sp.async = true;
    sp.src = 'http://example.com/widget/widget.js?key=248572180ede986058ede3519a25665e&r='+(new Date().getTime());
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(sp, s);
  })();
</script>
1
  • Go with a style tag instead of a link if you have a few styles. Commented Nov 27, 2016 at 2:07

1 Answer 1

1

here's a way you can add a stylesheet to your head tag:

head = document.head || document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = ""; // css link goes here
head.appendChild(link);

or you can create a style tag:

var css = ''; //put your css in here
head = document.head || document.getElementsByTagName('head')[0];
style = document.createElement('style');

style.type = 'text/css';
if (style.styleSheet){
   style.styleSheet.cssText = css;
} else {
   style.appendChild(document.createTextNode(css));
}

head.appendChild(style);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.