简体   繁体   English

在javascript中呈现HTML时包括外部CSS

[英]Include external CSS when rendering HTML inside javascript

I'm creating a tool that display a banner on a website when a simple javascript line is placed. 我正在创建一个在放置简单的javascript行时在网站上显示横幅的工具。 Something like this is enough to show the banner on any page. 这样的东西足以在任何页面上显示横幅。

<script type="text/javascript" src="http://mysite.com/mytool/"></script>

Basically its code is something like this 基本上它的代码是这样的

var div = document.createElement('div')
document.write('<div>all content goes here</div>');

Since its a 300 line app there is a lot of CSS involved. 由于它的300行应用程序涉及很多CSS。

Is there any way to embed an external CSS file when doing this inline HTML rendering via javascript? 通过javascript进行此内嵌HTML渲染时,有什么方法可以嵌入外部CSS文件?

I'm not using jQuery or any other library since I'm trying to reduce the output size as possible as I can. 我没有使用jQuery或任何其他库,因为我正在尝试尽可能减小输出大小。

You can print the link tag, as @Pointy pointed out: 您可以打印链接标记,就像@Pointy指出的那样:

document.write('<link href=stylesheet href=foo/style.css>');

But better is to place it in the head: 但更好的方法是将其放在头部:

document.head.innerHTML += '<link href=stylesheet href=foo/style.css>';
head = document.getElementsByTagName('head')[0],
style = document.createElement('link');
style.type = 'text/css';
style.href = "pathtocss.css"
style.rel = "stylesheet"
head.appendChild(style);

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

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