3

how to write a code in javascript that conditionally loads 2 different css styles I need to load a different css style for a page while it is loading and after it has loaded. i.e

if(condition)
{load 1 css};
else 
{load another css};
2
  • And why would you load a different stylesheet when the page is loading, that makes no sense ? Commented Sep 17, 2014 at 10:27
  • @close voters: I disagree that this is offtopic Commented Sep 17, 2014 at 10:27

3 Answers 3

6

You should be aware of the <link> tag's disabled feature.

<link rel="stylesheet" disabled="disabled" />

So, in your case, let us assume there are two stylesheets, day.css and night.css:

<link rel="stylesheet" href="day.css" id="day" />
<link rel="stylesheet" href="night.css" id="night" />

In your code, once you load, you can do this:

if (condition)
    document.getElementById('day').setAttribute("disabled", "disabled");

In case, you are using jQuery, it is more simpler! Use this:

if (condition)
{
    $("#day").prop("disabled", true);
    $("#night").prop("disabled", false);
}
else
{
    $("#day").prop("disabled", false);
    $("#night").prop("disabled", true);
}
Sign up to request clarification or add additional context in comments.

2 Comments

you where way faster than me to point the disabled feature so +1
Ha ha... Thanks, and I also took time to edit and format the question! :P
0

Alternative (jQuery based) solution:

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <script type="text/javascript">
    if (YOUR_CONDITION) {
        $(document.head).append('<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">');
    }
  </script>
</head>
<body>
  <h1>Hello world</h1>
</body>

Live demo

Compared to the disabled based solutions this only loads one CSS.

Comments

-1

Please use dynamic insertion of CSS file. refer code below.

function loadcssfile(filename){
    var fileref=document.createElement("link");
    fileref.setAttribute("rel", "stylesheet");
    fileref.setAttribute("type", "text/css");
    fileref.setAttribute("href", filename);
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
    }
    if(condition1)
        loadcssfile("mystyle1.css") ////dynamically load and add this .css file
    else if(condition2)
        loadcssfile("mystyle2.css") ////dynamically load and add this .css file`

1 Comment

Hi, using code you haven't written yourself without attribution isn't encouraged on Stack Overflow.

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.