TRIPTI RAWAL
TRIPTI RAWAL

Reputation: 39

how to write a code in javascript that conditionally loads 2 different css files?

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};

Upvotes: 3

Views: 579

Answers (3)

snehatulsi
snehatulsi

Reputation: 247

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`

Upvotes: -1

Matyas
Matyas

Reputation: 13702

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.

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

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);
}

Upvotes: 6

Related Questions