首页 > 解决方案 > 油脂猴 - 加载 html 和 css 时运行脚本

问题描述

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

真的没有等待样式的事件吗?

标签: javascriptgreasemonkeygreasemonkey-4

解决方案


GM 脚本有三个可能run-at的值 - 括号中是相应的 document.readyState

  • 文档开始(之前 document.readyState === 'loading'
  • 文档结尾 ( document.readyState === 'ineractive')
  • 文档空闲 ( document.readyState === 'complete')

这些是脚本唯一可用的注入点

在开始/结束时 - 还没有加载外部资源,所以对于你想要的来说太早了

在空闲时,所有外部资源都已加载,所以为时已晚

好的,你知道这一切,但我正在为其他未来的读者添加它

如果您在文档端加载脚本,则可以load向所有人添加侦听<link rel="stylesheet"

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
});

推荐阅读