Title: Jquery / Javascript Dynamically load CSS file (after runtime), replacing other css file?
Tags: javascript;jquery;css
Question: I've been reading up on how I can dynamically load a css file using jquery at the page's runtime, but haven't been able to find anything on this... what I am wondering if it is possible to basically re-load a css file to reflect changes from the server side..

The reason for this is that I am making an app that offers a number of different page layout sizes and I ran into some strange issues when doing modification of every css element on the page using jquery so I am making a server side script that will create a number of different css file that are identical, except for the sizes of the elements.. so I want to make it so I can dynamically load in a new version of this at any time and it will replace the original and reflect the changes in the page layout.. I am not sure if this is possible using the other scripts that do dynamic loading as it didn't seem to mention this use case. Thanks for any info.

Comment: Possible duplicate of [Load external css file like scripts in jquery which is compatible in ie also](https://stackoverflow.com/questions/2685614/load-external-css-file-like-scripts-in-jquery-which-is-compatible-in-ie-also)

Here is the accepted answer: We do something similar in our web app. The users can choose between several predefined layouts.

There is a static ```CSS``` file loaded normally with common styles shared by all layouts.

Then the function below receives a ```CSS``` string delivered by the server:

```var setStyle = function (css){
    //css has the format: selector{...style...}
    var styleNode, 
        cur = document.getElementById('_theme');
    cur &amp;&amp; cur.parentNode.removeChild(cur);

    styleNode = document.createElement('style');
    styleNode.setAttribute('type', 'text/css');
    styleNode.setAttribute('id', '_theme');
    document.getElementsByTagName('head')[0].appendChild(styleNode);

    if((/MSIE/).test(navigator.userAgent)){
        styleNode.styleSheet.cssText = css;
    }else{
        styleNode.appendChild(document.createTextNode(css));
    }
}
```

The function adds a ```STYLE``` tag with the id ```_theme``` and insert the ```CSS``` definition in it.
And the layout is applied to the page.
If the id ```_theme``` exists already, it is replaced.

More recently we developed a mobile version of our web app and we changed radically the technique.
The style is not defined by a static ```CSS``` anymore but from a ```JSON``` that we can generate dynamically, using variables, functions, etc... directly from the browser.

We made a small JS lib of it, the code is available at: http://github.com/pure/jstyle

Comment for this answer: Good info.. I'm curious why you would have changed the dynamic generation for the mobile app though.. I would think this would make the slower device (the phone) do more processing than normal since it js has to do at least some work in putting that json var into the layout.. I suppose its so the content will load incrementally on a slow connection instead of them waiting for the entire thing to load with the user seeing nothing until the entire css is loaded?
Comment for this answer: We did the desktop version first. I will move it to JS later as well. JS is fast enough, the DOM is slow in mobiles. If you plan to give some flexibility to people to change ie: fonts, colors, background; Using JS, variables, functions make it easier.

Here is another answer: ```function createjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 return fileref
}

function replacejscssfile(oldfilename, newfilename, filetype){
 var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist using
 var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
 var allsuspects=document.getElementsByTagName(targetelement)
 for (var i=allsuspects.length; i&gt;=0; i--){ //search backwards within nodelist for matching elements to remove
  if (allsuspects[i] &amp;&amp; allsuspects[i].getAttribute(targetattr)!=null &amp;&amp; allsuspects[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){
   var newelement=createjscssfile(newfilename, filetype)
   allsuspects[i].parentNode.replaceChild(newelement, allsuspects[i])
  }
 }
}

replacejscssfile("oldscript.js", "newscript.js", "js") //Replace all occurences of "oldscript.js" with "newscript.js"
replacejscssfile("oldstyle.css", "newstyle", "css") //Replace all occurences "oldstyle.css" with "newstyle.css"
```

From: http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 2.5', 'CreationDate': '2010:00:08/15/10', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><jquery><css>', 'Title': 'Jquery / Javascript Dynamically load CSS file (after runtime), replacing other css file?', 'ViewCount': 5084, 'id': 3489192, 'user_AboutMe': '<p>Web programmer with an interest in web task automation, building websites, etc, I prefer to do everything in Python now as I have moved to it from using a variety of other languages in the past. I also like to do front-end AJAX / javascript work but am moving to do this through Python as well, with the Pyjamas framework.</p>\n', 'user_AccountId': 159474.0, 'user_DisplayName': 'Rick', 'user_Reputation': 16173.0, 'user_Views': 854.0, 'user_id': 378874.0}}