instano.js - Alternate Stylesheet Method

Optimization using stylesheet modifications instead of element replacement.

by laucheukhim

HTML

<div class="nojs_init">Noscript Message 1</div>
<div class="nojs_init">Noscript Message 2</div>
<div class="nojs_init">Noscript Message 3</div>
<div class="nojs_init">Noscript Message 4</div>
<div class="nojs_init">Noscript Message 5</div>
<div class="nojs_init">Noscript Message 6</div>
<div class="nojs_init">Noscript Message 7</div>

JavaScript

var domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
      elm = document.createElement('div'),
      animation = false,
      animationstring = 'animation',
      keyframeprefix = '',
      pfx = '';

  if(typeof elm.style.animationName !== "undefined") { animation = true; }   

  if( animation === false ) {
    for( var i = 0; i < domPrefixes.length; i++ ) {
      if( elm.style[ domPrefixes[i] + 'AnimationName' ] !== undefined ) {
        pfx = domPrefixes[ i ];
        animationstring = pfx + 'Animation';
        keyframeprefix = '-' + pfx.toLowerCase() + '-';
        animation = true;
        break;
      }
    }
  }

if (animation) {

	function createStyleSheet(css, id) {
		var head = document.getElementsByTagName('head')[0],
			style = document.createElement('style');
		style.type = 'text/css';
		if (style.styleSheet){
		  style.styleSheet.cssText = css;
		} else {
		  style.appendChild(document.createTextNode(css));
		}
		if (id) {
			style.id = id;
		}
		head.appendChild(style);
		return style;
	}
	var animationDuration = 0.2;
	var nojsAnimation = 'from {width:0px;height:0px;visibility:hidden;opacity:0;} to {width:1px;height:1px;visibility:visible;opacity:1;}';
	var css = 	'.nojs_init { position:relative; vertical-align:top; ' + keyframeprefix + 'animation:nojs-animation1 ' + animationDuration + 's step-end; } ' + 
				'@' + keyframeprefix + 'keyframes nojs-animation1 { ' + nojsAnimation +' } ' + 
				'@' + keyframeprefix + 'keyframes nojs-animation2 { ' + nojsAnimation +' } ';
	createStyleSheet(css, 'nojs_style');
	function changeStyle(stylesheet, selectorText, fn)
	{
		var theRules = new Array();
		if (stylesheet.cssRules) {
			theRules = stylesheet.cssRules;
		} 
		else if (stylesheet.rules) {
			theRules = stylesheet.rules;
		}
		for (n in theRules)
		{
			if (theRules[n].selectorText == selectorText)   {
				fn(theRules[n].style);
			}
		}
	}
	var animationNumber = 1;
	function restartAnimation() {
		animationNumber = animationNumber === 1 ? 2 :...