Switch Themes Without a Page Refresh: Part 2

So in part one of this post we got all the CSS and other theme file we needed to stuck them in a document library.

With JavaScript you can change the CSS file a page uses without requiring a page refresh.  I have used this technique many times on non-SharePoint sites but there are some special challenges implementing this in SharePoint.  Most of the scripts I have used in the past use the alternate style sheet method as describred by A List Apart here. That method works fine but I had to find another way because I was already using that script to allow users to change the font size. After some research I found this script from CSS Newbie that worked pretty well without using alternate style sheets.

The problem

While the script works just fine on regular HTML pages it cause problems in SharePoint here is why :

[sourcecode language=”JavaScript”] $(“link”).attr(“href”,$(this).attr(‘rel’)); [/sourcecode]

This line of code basically finds all the linked CSS files in the page and changes thier value to point to the new style sheet you select.  This is fine on a site that just uses one CSS file but in SharePoint bad things happen.  In most cases we dont want to completely remove the reference to core.css. For most themes many elements don’t need to be changed so we only have to write the CSS to change them and let core.css do the rest.  If you remove core.css its like using a global reset (discussed in more detail here) which means you will have to restyle everything.  So them point is we want to leave core.css in the page and just add our theme.

To do this I had to make some changes to the master page to create to interface users will use to swap themes.

Switch Themes Without a Page Refresh: Part 1

Many sites offer the ability for users to change the color and style of the site to fit their preference.  SharePoint has this feature to some extend through themes but changing themes is not a very simple process and requires browsing to several pages.

With JavaScript you can change the CSS file a page uses without requiring a page refresh.  I have used this technique many times on non-SharePoint sites but there are some special challenges implementing this in SharePoint.  For this solution there were several requirements.

  • Users need to be able to switch themes and have the setting saved
  • No page refresh
  • Should be able to use both out of the box themes and custom themes

So first I needed to get the CSS files and images for the themes I wanted to use.  When you assign a theme to a site all the files for the theme are copied to a folder named _themes in the root of the site.

_themes folder

So what I did was assign each theme I wanted to use to the site one at a time.  With SharePoint designer I copied the files folders for each theme into a document library called Site Styles.  Each folder contains all the resources needed or the theme to work.