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.

Jason S
  • 184,598
  • 164
  • 608
  • 970
  • I apologize if this is a duplicate, I did do a google search but wasn't 100% sure what to look for. – Jason S Jul 25 '16 at 22:39
  • 2
    Try this: http://stackoverflow.com/questions/2685614/load-external-css-file-like-scripts-in-jquery-which-is-compatible-in-ie-also – Toby Jul 25 '16 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. – Jason S Jul 25 '16 at 22:44
  • You can look at the [source of the `loadCSS` library](https://github.com/filamentgroup/loadCSS/blob/master/src/loadCSS.js) (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. – David Gilbertson Jul 25 '16 at 23:49

2 Answers2

2

Try this:

Function:

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

Activate:

<button onclick="swapStyleSheet('dark.css')">Dark Style Sheet</button>
Toby
  • 12,743
  • 8
  • 43
  • 75
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");