简体   繁体   English

使用Javascript将css链接插入页面的头部

[英]Using Javascript to insert css link into the head of a page

I 3rd party site that includes this script: 我包含此脚本的第三方网站:

 var foo = "Hello World!";

      (function() {
        var foo = "Goodbye World!";
        document.write("<p class='something'>Inside our anomymous function foo means '" + foo + '".</p>');
       })();

I would now like to insert (using pure javascript) an external reference to a style sheet. 我现在想要(使用纯javascript)插入样式表的外部引用。 How can this be done? 如何才能做到这一点?

Using jquery you could do it like this: 使用jquery你可以这样做:

var css_link = $("<link>", { 
    rel: "stylesheet", 
    type: "text/css", 
    href: "style.css" 
});
css_link.appendTo('head');

however I need to keep this pure javascript. 但是我需要保持这个纯粹的JavaScript。

Quickly tried below in Chrome and it works.. 在Chrome下面快速尝试,它的工作原理..

var styleEl = document.createElement("link");
styleEl.type = "text/css";
styleEl.href = "style.css";
document.getElementsByTagName('head')[0].appendChild(styleEl);

Place a <script> tag in the head like this: 像这样在头部放置一个<script>标记:

<head>
    <script>
        document.write('<link rel="stylesheet" type="text/css" href="style.css">');
    </script>
</head>

The document.write() function appends whatever text you have as the parameter right where the script is. document.write()函数将您拥有的任何文本作为参数放在脚本所在的位置。

You can do it at runtime like this: 你可以在运行时这样做:

var css = document.createElement("LINK");
css.href = "style.css";
css.type = "text/css";
document.head.appendChild(css);

Edit: document.head is compatible with normal browsers and IE9+ 编辑:document.head与普通浏览器和IE9 +兼容

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

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