-
Reliably attaching CSS
In response to PPK's 24 ways article I thought I should describe the method I currently choose employ to hide elements onload. I have gone through this briefly in my article 'releasing the permalink slideshow'. As PPK mentioned, it is important to hide elements not needed for browsers that don't support JavaScript. The most important part of this hide technique is that there is no flicker in the period that the page is being loaded.
PPK suggests using document.write as to insert style elements inside the head. I propose instead using JavaScript's try / catch functionality to attach a stylesheet. Elements that need to be in the source for accessibility purposes, or need to be displayed for browsers without JavaScript, can then have a class that will hide them for browsers with JavaScript.
I like to use the try catch to ensure there are no issues in appending the link element to the head. The link contains the stylesheet that will then hide the elements that need to be hidden:
function setCSS(css) { try { // append stylesheet to alter document.getElementsByTagName("head")[0].appendChild(css); } catch (e) { setTimeout(function(){setCSS(css)}, 100); } } // create CSS element to set up the page var css = document.createElement("link"); css.setAttribute("href",path/to/stylesheet); css.setAttribute("rel","stylesheet"); css.setAttribute("type","text/css"); // attempt to add the css and then keep trying till we do setCSS(css); css = null;The setTimeout ensures that if there is an issue attaching the link to the bottom of the head (e.g. if the head hasn't finished loading when the link is trying to be attached) it retries after 100ms. Resetting the css variable to null avoids potential memory leaks.
-
Reliably attaching CSS
-
The Man in Blue > Resolution dependent layout update
The Man in Blue > Resolution dependent layout update — Update to the initial 2004 post on adding an additional stylesheet based on browser size.
