简体   繁体   English

在可嵌入的javascript代码中加载样式表。

[英]Loading Stylesheets in an embeddable javascript code.

So I built a widget that embeds into my clients website with some JS. 因此,我构建了一个小部件,该小部件使用一些JS嵌入到我的客户网站中。 The code that's being rendered requires some css so it looks and functions properly on the website. 呈现的代码需要一些CSS,因此它在网站上的外观和功能正常。 How should I go about including thse stylesheet and have it work with the code inside the javascript? 我应该如何包括这些样式表,并使其与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标签的一种方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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