将CSS添加到< head>使用JavaScript? [英] Add CSS to <head> with JavaScript?

查看:113
本文介绍了将CSS添加到< head>使用JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将javascript从javascript文件中的字符串添加到带有javascript的文档的头部?

Is there a way to add css from a string in the javascript file to the head of a document with javascript?

假设我们有一个网页lightbox脚本,此脚本需要一个css文件才能运行。

Let's say we have a webpage, which has a lightbox script, this script requires a css file to function.

现在使用< link> 添加此css文件将使css文件下载, t启用js。

Now adding this css file with <link> will make the css file download even for people that don't have js enabled.

我知道我可以动态加载css文件与脚本,但这也意味着将有2个http请求,如果有少到没有css在文件中我发现这个效率低下。

I know that I can dynamically load the css file with the script, but that also means that there will be 2 http requests, and in cases where there is little to no css in the file I find this inefficient.

所以我想到自己,如果你可以把css文件中的css放入脚本,让脚本解析css并将其添加到头部,或者甚至更好地只有脚本将css直接添加到文档的< head> 中。

So I thought to myself, what if you could put the css that you have in the css file, into the script, have the script parse the css and add it into the head, or even better just have the script add the css directly into the <head> of the document.

但是我没有在网上发现这是可能的,所以可以用js添加css到头部?

But I have found nothing online that suggests that this is possible, so is it possible to add css to the head with js?

我编辑roryf的工作交叉浏览器的答案(IE5除外)

I edited roryf's answer to work cross browser (except IE5)

JavaScript:

Javascript:

 function addcss(css){
    var head = document.getElementsByTagName('head')[0];
    var s = document.createElement('style');
    s.setAttribute('type', 'text/css');
    if (s.styleSheet) {   // IE
        s.styleSheet.cssText = css;
    } else {                // the world
        s.appendChild(document.createTextNode(css));
    }
    head.appendChild(s);
 }


推荐答案

依赖于javascript库,可以使用 document.write()来输出所需的css,包装在 style 标签,直接进入文档 head

If you don't want to rely on a javascript library, you can use document.write() to spit out the required css, wrapped in style tags, straight into the document head:

<head>
  <script type="text/javascript">
    document.write("<style>body { background-color:#000 }</style>");
  </script>
  # other stuff..
</head>

这样可以避免触发额外的HTTP请求。

This way you avoid firing an extra HTTP request.

还有其他解决方案,建议/添加/删除,但我没有看到任何点,过度复杂的东西,已经工作良好的跨浏览器。祝你好运!

There are other solutions that have been suggested / added / removed, but I don't see any point in overcomplicating something that already works fine cross-browser. Good luck!

http://jsbin.com/oqede3/edit

这篇关于将CSS添加到&lt; head&gt;使用JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆