Dynamically load stylesheets

12,759

Solution 1

You should look into asychronously loading assets, such as the famous google-analytics code. You can load external stylesheets using Javascript.

JavaScript

(function(){
  var styles = document.createElement('link');
  styles.rel = 'stylesheet';
  styles.type = 'text/css';
  styles.media = 'screen';
  styles.href = 'path/to/css/file';
  document.getElementsByTagName('head')[0].appendChild(styles);
})();

Lines 1 and 7 create a new scope for variables such that local variables do not collide or override with globally scoped variables. It isn't necessary just a best practice. This solution also assumes you have a <head> tag in your html.

Solution 2

You can add/remove/edit link tags in your head area with java script to add/remove stylesheet files.

Code example:

Add a stylesheet to the head:

var newstyle = document.createElement("link"); // Create a new link Tag
// Set some attributes:
newstyle.setAttribute("rel", "stylesheet");
newstyle.setAttribute("type", "text/css");
newstyle.setAttribute("href", "filename.css"); // Your .css File
document.getElementsByTagName("head")[0].appendChild(newstyle);

To remove or edit a stylesheet you can give every stylesheet an id attribute and access it with this:

document.getElementById('styleid')

Or you can loop through all link tags in the head area and find the correct one but I suggest the solution with the ID ;)

Now you can change the href attribute:

document.getElementById('styleid').setAttribute("href", "newfilename.css");

Or you can remove the complete tag:

var styletorem = document.getElementById('styleid');
styletorem.parentNode.removeChild(styletorem)

Solution 3

I just tried to give dynamic styling to my webpage. I used a button. On click of it, the CSS will get imported using a method in Javascript.

In my html, I have:

<button type="button" onclick="changeStyle()"> CLICK TO SEE THE MAGIC!! </button>

Then in Javascript, I have a method named changeStyle():

  function changeStyle()
  {
    var styles = document.createElement('link');
    styles.type="text/css";
    styles.rel="stylesheet";
    styles.href="./css/style.css";
    document.head.appendChild(styles);
 }

It worked perfectly.

Share:
12,759
Anshu Dwibhashi
Author by

Anshu Dwibhashi

In a nutshell... Artificial Intelligence specifically Machine Learning &amp; Natural Language Processing Web Development and App Development Python, C++, Java

Updated on July 23, 2022

Comments

  • Anshu Dwibhashi
    Anshu Dwibhashi almost 2 years

    i know that you can have style-sheets in the head of a page, but i like to have them in a separate file. Now i'm working with a single page application.

    Well in an SPA the content is dynamic, right? so i didn't want to import all the style-sheets in the head section with the link tag. Can i somehow import style-sheets as-and-when i need them?

    I mean, can i have a link in the body, such that whenever my SPA loads some dynamic content, a style sheet also gets loaded? Such that i dont have to load all the stylesheets even when the dynamic content is not loaded..

    I stress again: Whenever the content loads, the styles load.

    I know i can do it with the help of an inline style like this:

    ~PSEUDO CODE 
    <tagname style="somestyle"></tagname>
    

    but can i have some dynamic file imports too? Can i have the link tag in the body too? Even if it works, is it standard?

  • Anshu Dwibhashi
    Anshu Dwibhashi over 10 years
    can i do that dynamically? i mean, in the beginning i'll have imported 'main.css' but how do i dynamically import files as i load content
  • virtualmarc
    virtualmarc over 10 years
    yes. the browser should rerender the current view on dom change. So if you add or remove stylesheets the change happens directly in the browser. You can test this also with the developer console of your browser. just remove, add or change a stylesheet's link tag there and the style change should be seen directly
  • Anshu Dwibhashi
    Anshu Dwibhashi over 10 years
    can you please give example with code, i understand code better you see :)
  • Anshu Dwibhashi
    Anshu Dwibhashi over 10 years
    okay, thanks, but will it actually load it or just create a dummy node it the doc. structure ?
  • cjross
    cjross over 10 years
    It will load, bring dev tools drop it in the console with a sample link such as cdn CSS file from cdnjs.com and view the proof in the network tab
  • Adria
    Adria almost 9 years
    There is always a head, even if you don't explicitly create one.
  • stackg91
    stackg91 over 4 years
    Is there any way to know when the dynamically added stylesheet is actually loaded? I am adding content which is affected by the stylesheet this looks bad since its visible without styles until the stylesheet is done loading