I'm building a userscript and to avoid the dreaded 'jittering' effect as the userscript edits the page's styles once the page has finished rendering I'm attempting to do it while the page is still loading.
Doing this by inserting rules into a pre-existing style object works as expected....
http://pastebin.com/NNjLjKA5 ...wait until a style object exists then add a new style to it.
However when trying to create a new style object to insert the rules into I'm experiencing weird behavior...
// ==UserScript==
// @name script
// @include *
// @run-at document-start
// ==/UserScript==
// Add style rules while page is loading (to prevent jumping)
function addStyleRules(){
// Check if stylesheets exist yet, if not try again in a bit
if( !document.styleSheets[0] ) return setTimeout( addStyleRules,1 );
// Get/create stylesheet element (if not already created)
if( !document.querySelector( 'style[title=new_stylesheet]' ) ){
var css = document.createElement( 'style' );
css.type = "text/css";
document.head.appendChild( css );
css.title = 'new_stylesheet';
}
// Get stylesheet object
var ss;
for(i in document.styleSheets )
if( document.styleSheets[i].title == 'new_stylesheet' )
ss = document.styleSheets[i];
// Add style rules
if(ss.addRule)
ss.addRule( '*','background-color:black',0);
else
ss.insertRule('*{background-color:black}',0);
//debug
console.log( 'page loading', ss, new Date().getTime() );
}
addStyleRules();
// Page has finished loading
document.addEventListener('DOMContentLoaded',function(e){
// Get stylesheet object
var ss;
for(i in document.styleSheets )
if( document.styleSheets[i].title == 'new_stylesheet' )
ss = document.styleSheets[i];
//debug
console.log('page loaded', ss, new Date().getTime() );
});
This script should create a new style element, find the new style object in 'document.styleSheets', then apply a new rule.
It seems to do this fine, as observed by the first log event. However once the page has finished loading the new style object no longer exists (even though the style element is present in the DOM).
So yeah, my question is...
What's happening to the newly created stylesheet object in between it being created, having a new rule successfully applied, and the 'DOMContentLoaded' event firing?
- Browser is Chrome 16.0.912.77