0

I have a page that allows users to dynamically change the loaded theme (stylesheet). I have a themeStyle <link> element that stores the currently loaded stylesheet. I'm switching it like this

function switchTemplate(stylePath){
    var ns = $('<link>', {
            href: stylePath,
            id: 'themeStyle',
            type: 'text/css', 
            rel: 'stylesheet'
        });
    $('#themeStyle').replaceWith(ns);
    self._cssIsLoaded(ns.get(0), stylePath);

}

and then using this function to detect if it's loaded.

It was working sporadically, but I realized it was probably never working because the #themeStyle css will always be loaded, but not necessarily changed.

I added passing the css file path to the _cssIsLoaded function, but it changes before the load is complete, so I don't know what to use to check if it has switched.

The only solution I can think of now is to have a hidden div stylePath to it as content: element in every stylesheet, and check if that div's content is the correct stylePath... but that requires changing every stylesheet, the HTML and the JS as well as just being somewhat cludgy. Is there any more reasonable way to achieve this?

edit: I've thought of just adding the new styles at the end, but there's possibility that not all the styles will be overridden by the new one. There's a base stylesheet always in place and these particular rules being loaded only affect one part of the page.

Community
  • 1
  • 1
Damon
  • 10,493
  • 16
  • 86
  • 144

2 Answers2

1

A simple solution would be using JS to change the class on the body element. I would then have 2 sets of css. Each set would have all its selectors prefixed with the class you put on the body element. So something like

<link href="theme1.css" /> 
contains:
body.theme1 a { color: #ff000; }

<link href="theme2.css" />
contains:
body.theme2 a { color: #0000ff; }
Nat Darke
  • 871
  • 7
  • 3
  • that's a little more elegant than how I was thinking. I would really like a way that doesn't require me to change all of my CSS files, or load large numbers of CSS files on top of each other, though. The reason I need the 'load complete' functionality is for js to respond to different locations of certain elements – Damon Sep 09 '11 at 13:16
0

I settled on adding an incrementing number after the id of the style tag, when I switch the style, I add the new stylesheet and remove the old one, then check with the new number to see if it has been loaded.

function switchTemplate(stylePath){
    var osid = $('[id^="themeStyle-"]');
    var stylenum = osid[0].id.split('-')[1];
    var newstylenum = (Number(stylenum) + 1).toString();
    var ns = $('<link>', {
            href: stylePath,
            id: 'themeStyle-' + newstylenum,
            type: 'text/css', 
            rel: 'stylesheet'
        });
    $("head").append(ns);
    $('#themeStyle-' + stylenum).remove();
    _cssIsLoaded(ns.get(0), stylePath);
}
Damon
  • 10,493
  • 16
  • 86
  • 144