javascript - 油脂猴 - 加载 html 和 css 时运行脚本
问题描述
正如标题所说,我想等到 html 被解析,并且所有样式表都被加载,因为我需要使用currentsyle
. 但是,我不想等待图像。所以我不能使用load
事件,因为它等待图像。而且我不能使用该DOMContentLoaded
事件,因为它不等待样式表。我也不能使用document.body.appendChild
在文档末尾添加脚本标记,因为该脚本是在假设页面上的 javascript 被禁用的情况下运行的。
真的没有等待样式的事件吗?
解决方案
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
});
推荐阅读
- .htaccess - 更改浏览器 URL,而不是实际路径或文件位置
- vb.net - 模块真的与 SharedMembers-NotInheritable-PrivateNew 类相同吗?
- mongodb - Docker Mongodb:MongoNetworkError:连接 ECONNREFUSED 192.168.96.2:27017
- php - 如何在codeigniter中获取用户和配置文件表数据
- node.js - 在 forEach 循环中处理 Promise
- php - 新列的回滚会删除整个表
- sql - 从选择列表中的引用表中选择第 N 行的一列
- hazelcast - Hazelcast 锁在其他成员离开集群时被释放
- sql-server - 过滤器为空的情况 - 全选
- linux - 使用 CURL 或 WGET 从 google firebase 存储下载文件