Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript greasemonkey-加载html和css时运行脚本_Javascript_Greasemonkey_Greasemonkey 4 - Fatal编程技术网

Javascript greasemonkey-加载html和css时运行脚本

Javascript greasemonkey-加载html和css时运行脚本,javascript,greasemonkey,greasemonkey-4,Javascript,Greasemonkey,Greasemonkey 4,正如标题所说,我想等到html被解析,所有样式表都被加载,因为我需要使用currentsyle。但是,我不想等待图像。所以我不能使用load事件,因为它会等待图像。我不能使用DOMContentLoaded事件,因为它不等待样式表。我也不能使用document.body.appendChild在文档末尾添加脚本标记,因为该脚本是在页面上的javascript被禁用的假设下运行的 是否严重没有等待样式的事件?对于GM脚本,可能有三个以值运行-括号中有相应的document.readyState

正如标题所说,我想等到html被解析,所有样式表都被加载,因为我需要使用
currentsyle
。但是,我不想等待图像。所以我不能使用
load
事件,因为它会等待图像。我不能使用
DOMContentLoaded
事件,因为它不等待样式表。我也不能使用
document.body.appendChild
在文档末尾添加脚本标记,因为该脚本是在页面上的javascript被禁用的假设下运行的


是否严重没有等待样式的事件?

对于GM脚本,可能有三个
值运行-括号中有相应的document.readyState

  • 文档开始(
    document.readyState==='loading'
    之前)
  • 文档结束(
    document.readyState===“ineractive”
  • 文档空闲(
    document.readyState===“完成”
这些是脚本唯一可用的注入点

在开始/结束时-尚未加载任何外部资源,因此对于所需内容来说太早了

在空闲状态下,所有外部资源都被加载,对于您想要的东西来说太晚了

好的,你知道所有这些,但我将为其他未来的读者添加它


如果您在文档末尾加载脚本,您可以将
load
侦听器添加到所有
中,这是一个非常优雅的解决方案。但是,如果脚本在加载样式表或加载失败后运行,则它不会运行。我测试了一个案例,其中uMatrix阻止了样式表,在这种情况下它不会运行,因为样式表在用户脚本运行之前就被阻止了。有没有办法检查样式表是否加载失败或加载完成?关于
setTimeout
,请参阅编辑的代码@user234683@user234683-我对代码做了一些编辑,因此,在
.then
中,您可以反复查看结果,以查看加载的内容和未加载的内容-可能对您的userscript的开发阶段很有用我的userscript在所有网站上运行,因此我不能对样式表做任何假设。我想暂停一下会很糟糕的。如果没有其他人提出检测样式表是否加载失败的想法,我会在几天后将此标记为答案。我认为失败应该触发一个错误事件——甚至一个超时事件——当其中一个样式表失败时,您在控制台中看到了什么?
Promise.all(Array.from(document.querySelectorAll('link[rel="stylesheet"]'), ss => new Promise(resolve => {
    const href = ss.href;
    const fulfill = status => resolve({href, status});
    setTimeout(fulfill, 5000, 'timeout');
    ss.addEventListener('load', () => resolve('load'));
    ss.addEventListener('error', () => resolve('error')); // yes, resolve, because we just want to wait until all stylesheets are done with, errors shouldn't stop us
}))).then((results) => {
    // results is an array of {href:'some url', status: 'load|error|timeout'}
    // at this point stylesheets have finished loading
});