Patel
Patel

Reputation: 585

How to load in an external CSS file dynamically?

I'm trying to create a dynamic page using external .css pages where the page color will get changed. Below is my code. But when I click the href, I am not getting any output. Can anyone please tell me what's the problem in my code?

<script language="JavaScript">
function loadjscssfile(filename, filetype)
{
    if (filetype=="css")
    { 
        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)
}

loadjscssfile("mystyle.css", "css") 
</script>
<a href="javascript:loadjscssfile('oldstyle.css','css')">Load "oldstyle.css"</a> 

I have modified my code as below. Still, I'm facing the problem of getting the output. No result. Can anyone please help me out?

<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="css/newstyle.css" />
<script language="JavaScript" type="text/javascript">
function loadjscssfile(filename, filetype)
{
    if (filetype=="css") 
    {
        var fileref = document.createElement("link");
        fileref.rel = "stylesheet";
        fileref.type = "text/css";
        fileref.href = "filename";
        document.getElementsByTagName("head")[0].appendChild(fileref)
    }
}
loadjscssfile("oldstyle.css", "css") 
</script>
<a href="javascript:loadjscssfile('oldstyle.css','css')">Load "oldstyle.css"</a> 
</head>

Upvotes: 19

Views: 47478

Answers (9)

Tim Goodman
Tim Goodman

Reputation: 23976

Try this:

var fileref = document.createElement("link");
fileref.rel = "stylesheet";
fileref.type = "text/css";
fileref.href = filename;
document.getElementsByTagName("head")[0].appendChild(fileref)

Upvotes: 29

Joseph Van Riper
Joseph Van Riper

Reputation: 616

I did not like the idea of adding additional links to the document, as it leads to a memory leak.

Instead, I tried something else.

In the document's head:

<head>
<link id="changeme" rel="stylesheet" type="text/css" href="css/oldstyle.css" />
<!-- moar stuff hear -->
</head>

In JavaScript:

<script language="JavaScript">
function loadFile(filename) {
  const link = document.querySelector("#changeme");
  link.href = filename;
}
const sheets = ["/css/theme1.css", "/css/theme2.css", "/css/theme3.css"];
let pos = 0;
let timer = setInterval(()=>{
  loadFile(sheets[pos]);
  pos = pos + 1;
  if (pos >= sheets.length) {
    pos = 0;
  }
}, 2000);
</script>

This simply replaces the href already in your head, easily identified using a handy id. In this sample, every two seconds it moves from theme1 to theme2, to theme3, back to theme1 again, until someone leaves the page. Great for indecisive websites.

(I have no idea how portable this is, so caveat emptor... but it works on Firefox and Chromium, which was good enough for my needs).

Upvotes: -1

chirag
chirag

Reputation: 89

Use this code

document.getElementsByTagName("head")[0].appendChild('<link href="style.css" rel="stylesheet" type="text/css" />');

it might work, your code may working but due to some another css it won't reflected.

Upvotes: 0

user250418
user250418

Reputation: 51

Try adding a style line in your html and just using @import in the css to get the new file

Upvotes: 1

vilhalmer
vilhalmer

Reputation: 1159

Tim Goodman's answer is correct, but instead of fileref.href = "filename"; it should be fileref.href = filename;

Otherwise you're trying to load a file with the name "filename" rather than what you passed to the script.

Alternately, if you're willing to use the jQuery library, this can be accomplished in one line:
$("head").append("<link rel='stylesheet' id='extracss' href='"+filename+"' type='text/css' />");

Also, about the first version of your script using setAttribute: Most browsers will only take setAttribute with an empty third parameter because of the way the spec is set up:
fileref.setAttribute("href", filename, "");

Upvotes: 16

Chetan S
Chetan S

Reputation: 23803

First of all, you can't have an anchor element in the <head> section. Secondly, are you sure your CSS path is correct? I'm asking because you already have a reference to css/newstyle.css but your are trying to load newstyle.css. Are you sure it's not css/newstyle.css?

Edit: Here is a working example of your own code. There is something else wrong. Try to statically link the CSS and see if you are getting the styles. If not, there may be errors in your stylesheet.

By statically linking the stylesheet, I meant to say add this in your page instead of loading from javascript

<link rel="stylesheet" type="text/css" href="css/oldstyle.css" />

Upvotes: 0

T.Raghavendra
T.Raghavendra

Reputation: 362

Change this

<a href="javascript:loadjscssfile('oldstyle.css','css')">Load "oldstyle.css"</a> 

to

<a href="javascript:void(0)" onclick="loadjscssfile('oldstyle.css','css');">Load "oldstyle.css"</a> 

I belive the onclick, event to href will reload the new file.

Upvotes: 0

pib
pib

Reputation: 3313

That code should work, except perhaps you might want to add type="text/javascript" to your script tag.

I tested the code via Firebug and it worked for me.

Maybe the problem is that your original stylesheet is still included in the page and thus overriding the style of your secondary stylesheet?

Upvotes: 0

chirag
chirag

Reputation: 89

' document.createElement("link") ' creates hyper link object, not css style tag() element, so you are not able to apply this dynamically

correct me if i am wrong

Upvotes: -7

Related Questions