替代 "Load" 监听器以加载 HTMLcollection 元素

Alternative to "Load" listener in order to load HTMLcollection elements

我正在使用 Tampermonkey 在网页上 运行 一些 JavaScript。

我正在使用 x = document.getElementsByClassName("class") 因为我需要 x 的长度和元素;但在过去几周,旧代码不起作用,所以我不得不更改它并添加一个“加载”事件监听器(在没有事件监听器行的情况下工作之前):

x = document.getElementsByClassName(" class ");

window.addEventListener("load", function(event) {
  sw = x.length; //(length of x is always between 0 and 4)
  switch (sw) {
    case 1:
      //do something with x[0] and reload after timeout;
      break;
    case 2:
      //do something with x[0] x[1] and reload after timeout
      break;
    case 3:
      //do something with x[0] x[1] x[2] and reload after timeout
      break;
    case 4:
      //do something with x[0] x[1] x[2] x[3] and reload after timeout
      break;
    default:
      setTimeout(function() {
        location.reload();
      }, RandomReloadTime * 1000);
      break;
  }
});

我需要一直以运行一直以来,所以我的问题是当标签不活跃时(通常在我睡觉时,PC ON,打开tab,但[= 33) =] 将选项卡置于 'sleep'), 网页未加载,因此侦听器未激活;

总而言之,我想做的是(使用 Tampermonkey):

还有其他方法吗?

window.addEventListener("load", function(event) { ... } 更改为 $( document ).ready(function() { ... } 后,脚本的行为符合我的预期。

显然,我不需要加载整个页面来使用 DOM 中的元素,只需要加载 DOM,这可以通过第二个命令完成.最好解释差异here

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.