简体   繁体   中英

Loading Stylesheets in an embeddable javascript code.

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM