简体   繁体   English

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

[英]greasemonkey - run script when html and css is loaded

As the title says, I want to wait until the html is parsed, and all stylesheets are loaded, because I need to use currentsyle .正如标题所说,我想等到 html 被解析,并且所有样式表都被加载,因为我需要使用currentsyle However, I do not want to wait for images.不过,我希望等待的图像。 So I cannot use load event, as that waits for images.所以我不能使用load事件,因为它等待图像。 And I can't use the DOMContentLoaded event, as that doesn't wait for stylesheets.而且我不能使用DOMContentLoaded事件,因为它不等待样式表。 I also cannot use document.body.appendChild to add a script tag at the end of the document because this script is being run under the assumption that javascript on the page is disabled.我也不能使用document.body.appendChild在文档末尾添加脚本标记,因为此脚本是在页面上的 javascript 被禁用的假设下运行的。

Is there seriously no event to wait on styles?难道真的没有事件等待style?

There are three possibly run-at values for GM scripts - with corresponding document.readyState in brackets GM 脚本有三个可能的run-at值 - 括号中是相应的 document.readyState

  • document-start ( before document.readyState === 'loading' )文档开始(document.readyState === 'loading'
  • document-end ( document.readyState === 'ineractive' )文档结束( document.readyState === 'ineractive'
  • document-idle ( document.readyState === 'complete' )文档空闲( document.readyState === 'complete'

These are the only available injection points for your script这些是您的脚本唯一可用的注入点

at start/end - no external resources will be loaded yet, so too early for what you want在开始/结束时 - 还没有加载任何外部资源,所以你想要的还为时过早

at idle, all external resources are loaded, so too late for what you want在空闲时,所有外部资源都已加载,所以为时已晚

OK, you know all this, but I'm adding it for other future readers好的,你知道这一切,但我正在为其他未来的读者添加它

if you load your script at document-end, you can add load listeners to all <link rel="stylesheet" like如果您在文档末尾加载脚本,则可以将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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM