0

Is there a way to add a <link rel="stylesheet" type="text/css"> with the URL dynamically-selected based on some Javascript expression evaluation?

(without using jQuery or other external library -- I want to avoid dependencies on external libraries.)

In particular I want to run some Javascript during or as a result of pageload, rather than at a later date, but I do want to make sure the CSS that has been replaced or added gets loaded as a result of running that Javascript.

4
  • I apologize if this is a duplicate, I did do a google search but wasn't 100% sure what to look for. Commented Jul 25, 2016 at 22:39
  • 2
    Try this: stackoverflow.com/questions/2685614/… Commented Jul 25, 2016 at 22:41
  • that helps, I'm looking for something with pure Javascript, no library dependencies. But I guess I can figure it out from there, doesn't look like jquery is doing anything fancy. Commented Jul 25, 2016 at 22:44
  • You can look at the source of the loadCSS library (a lib for async CSS loading) to see the tricks they use to get the CSS to apply without re-loading the page. It's a bit full on if you're new to JS though. Commented Jul 25, 2016 at 23:49

2 Answers 2

2

Try this:

Function:

function swapStyleSheet(sheet){
    document.getElementById('pagestyle').setAttribute('href', sheet);
}

Activate:

<button onclick="swapStyleSheet('dark.css')">Dark Style Sheet</button>
Sign up to request clarification or add additional context in comments.

6 Comments

Obviously you can use window.onload for it to run when the page loads rather than by a button.
pagestyle is a standard crossbrowser DOM element?
OH, never mind, you must mean I put the ID where I want it and use javascript. That's clever.
and this will always trigger a CSS reload?
Not necessarily - if you switch to a <a href="#"> instead of a button it will trigger a reload.
|
2

You are welcome to try this function.

function addStylesheet(file) {
    var
        head = document.getElementsByTagName("head")[0],
        style = document.createElement("link");
    style.rel = "stylesheet";
    style.type = "text/css"; //optional
    style.href = file;
    head.appendChild(style);
}

addStylesheet("style.css");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.