|
As part of a recent request to customize the header of a SharePoint (MOSS 2007) site, I ran into a little problem when trying to dynamically replace a stylesheet using Javascript. The page had two stylesheets loading, one core stylesheet and one theme stylesheet, in that order. I was trying to replace the core stylesheet with an altered version for certain parts of the site, however when I did it was as if the theme stylesheet was being overwritten too. The problem was in how IE handles the DOM and Stylesheets (this was not a problem in Firefox). I started by creating a new stylesheet link element, then replacing the existing one with the new one (see code below). var newElement = document.createElement("link"); newElement.type = "text/css"; newElement.rel = "stylesheet"; newElement.href = "/_layouts/1033/styles/core_orig.css"; newElement.media = 'screen';var oHead = document.getElementsByTagName("head")[0]; var aLinks = oHead.getElementsByTagName("link"); for (var li = 0; li < aLinks.length; li++) { if (aLinks.href.indexOf("core.css") > -1) { oHead.replaceChild(newElement, aLinks[li]); } } This was the first instance of seeing the problem with my theme.css being overwritten. I then tried just doing a simple replace on the link href to replace core.css with core_orig.css. Again, the same results. In both cases it seemed as if the replace just wasn't happening at all. After some exploring using the ever helpful Firebug and the IE Dev Toolbar I realized the replace was happing, it just wasn't behaving as expected. So finally I realized it was just a matter of the order of things occuring, as it often is. In this case, IE was loading core.css, then theme.css then in javascript I was loading core_orig.css which because of similar classes was basically overwritting them both. In Firefox this wasn't an issue as it just replaced the core.css as I wanted but IE reinterpreted it again after the other two had already loaded. So now all I had to do was just drop and recreate the theme.css after replace the core.css and I was done (final code below). var url=window.location.href.toLowerCase(); if (url.indexOf('/sites/') > -1 || url.indexOf('/sitedirectory/') > -1) { var oHead = document.getElementsByTagName("head")[0]; var aLinks = headID.getElementsByTagName("link"); var newElement = document.createElement('link'); newElement.type = 'text/css'; newElement.rel = 'stylesheet'; newElement.href = '/_layouts/1033/styles/core_orig.css'; newElement.media = 'screen'; for (var ci = 0; ci < aLinks.length; ci++) { if (aLinks[ci].href.indexOf('core.css') > -1) { var newHref = aLinks[ci].href; newHref = newHref.replace("core.css", "core_orig.css"); newElement.href = newHref; oHead.replaceChild(newElement, aLinks[ci]); } else if (aLinks[ci].href.indexOf('/_themes/') > -1) { var newNode = aLinks[ci].cloneNode(); oHead.removeChild(aLinks[ci]); oHead.appendChild(newNode); } } }
Relevant Tags: CSS | JavaScript | SharePoint
[ Back to previous page ]
|