1

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. How can this be done?

Using jquery you could do it like this:

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

however I need to keep this pure javascript.

3 Answers 3

3

Quickly tried below in Chrome and it works..

var styleEl = document.createElement("link");
styleEl.type = "text/css";
styleEl.href = "style.css";
document.getElementsByTagName('head')[0].appendChild(styleEl);
Sign up to request clarification or add additional context in comments.

Comments

0

Place a <script> tag in the head like this:

<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.

1 Comment

I think OP means at runtime.
0

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+

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.