Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load and unload stylesheets

I've searched various posts and forums but can't find the right answer. I need to find a way to dynamically load and unload stylesheets.

I'm building a website that has a main stylesheet and 2 optional stylesheets, for example purposes i'm going to use colours. I need to add 2 links, that loads a new stylesheet on click. This stylesheet will override some of the styles from the main stylesheet.

For example:

I have a yellow website, this is what most people want, however i've got the option for the user to click red or blue, when they do, the styles in the red stylesheet override the main styles and change the website to red, if they click blue this changes to blue.

To complicate things further, if the user clicks red and loads the red stylesheet and they changed their mind and now want blue, I need the red stylesheet to unload and just load the blue.

I'm not very proficient with javascript so am having issues with this.

Thanks in advance!

like image 405
kala233 Avatar asked Apr 02 '12 15:04

kala233


People also ask

How do I load a CSS file dynamically?

Load CSS and JS files dynamically: We create a script element for the JS file and link element for the CSS file as required using DOM, assign the appropriate attributes to them, and then add the element to the desired location within the document tree using the element. append() method.

Can we change CSS dynamically?

color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id . You could also use setAttribute(key, value) to set a style on an element. For example, you could set the colour of an element to red by calling element.

How do I make my CSS file load faster?

To optimize the CSSOM construction, remove unnecessary styles, minify, compress and cache it, and split CSS not required at page load into additional files to reduce CSS render blocking.


2 Answers

To Load css dynamically

var headID = document.getElementsByTagName("head")[0];
var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = 'FireFox.css';
cssNode.media = 'screen';
headID.appendChild(cssNode);

To Unload css file

function removefile(filename, filetype) {
var targetElement = "link"; 
var targetAttr = "href"; 

var allCtrl = document.getElementsByTagName(targetElement);
for (var i=allCtrl.length; i>=0; i--)  { //search backwards within nodelist for matching elements to remove
if (allCtrl[i] && allCtrl[i].getAttribute(targetAttr)!=null && allCtrl[i].getAttribute(targetAttr).indexOf(filename)!=-1);
allCtrl[i].parentNode.removeChild(allCtrl[i]);
}
}
like image 163
newTag Avatar answered Sep 17 '22 21:09

newTag


I managed to get this working with a little tweaking of:

http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml

Content of the link:

function loadjscssfile(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)
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

function removejscssfile(filename, filetype){
    var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
    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>=0; i--){ //search backwards within nodelist for matching elements to remove
    if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
        allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
    }
}

removejscssfile("somescript.js", "js") //remove all occurences of "somescript.js" on page though in most browser this does not unload the script
removejscssfile("somestyle.css", "css") //remove all occurences "somestyle.css" on page

Just FYI: For js scripts, this will remove a script element from the DOM but most browser will not unload the js code i.e. anything defined in the js file will stay defined.

like image 32
kala233 Avatar answered Sep 17 '22 21:09

kala233