Search code examples
javascriptaddeventlistenertampermonkeyhtmlcollection

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


I am using Tampermonkey to run some JavaScript on a webpage.

I am using x = document.getElementsByClassName("class") because I need the length and the elements of x; but in the last weeks, the old code did not work, so I had to change it and add a "load" event listener (Before it worked without the event listener line):

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

I need this to be running all the time, so my issue is that when the tab is not active (usually during the night when I sleep, PC on, tab opened, but Chrome puts the tab to 'sleep'), the webpage is not loaded, hence the listener is not activated;

To summarize, what I want to do is (using Tampermonkey):

  • Add elements of that class to X.
  • Use elements added in X and reload to do it all over again

Is there another way in which I can do this?


Solution

  • After changing window.addEventListener("load", function(event) { ... } with $( document ).ready(function() { ... } , the script behaved as I expected.

    Apparently, I did not need the whole page to be loaded in order to use elements from the DOM, just the DOM needed to be loadedl and that can be done with the second command. The difference is best explained 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.