我正在构建一个userscript并避免可怕的'抖动'效果,因为userscript在页面完成呈现后编辑页面的样式我试图做到这一点该页面仍在加载。在目标页面加载完成前添加一个样式元素
通过插入规则到一个预先存在的样式对象,这样做可以按预期工作....
http://pastebin.com/NNjLjKA5 ......等到一个风格对象是否存在,然后添加一个新的样式,。
试图进入我遇到怪异的行为,以创建一个新的样式对象插入规则然而,当...
// ==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());
});
这个脚本应该创建一个新的风格元素,找到新'document.styleSheets'中的样式对象,然后应用新规则。
它似乎做得很好,正如第一次日志事件所观察到的那样。但是,一旦页面加载完成,新的样式对象不再存在(即使样式元素存在于DOM中)。
所以,是的,我的问题是...
发生了什么事,以创建之间就新创建的样式表对象,其成功地应用新规则,和“DOMContentLoaded”事件触发?
- 浏览器是由铬16.0.912.77