Guesser
Guesser

Reputation: 1857

on ready state change multiple times

I'm using this method to set a function for when the page is loaded.

It works fine but I want to actually call various set of functions on different pages. The problem is each time I include this code overwrites the previous one so only one function is launched on page load.

document.onreadystatechange = function () {
  var state = document.readyState
  if (state == 'interactive') {

  } else if (state == 'complete') {
    myFunc();
  }

}

So how would I add functions instead of creating a new one for onreadystatechange each time?

Upvotes: 3

Views: 2305

Answers (1)

BCDeWitt
BCDeWitt

Reputation: 4773

If I'm understanding you correctly, you need document.addEventListener(). This approach allows you to assign multiple functions to the same event.

Combination of info and example code found on MDN:

document.addEventListener('readystatechange', function(evt) {
  switch (evt.target.readyState) {
    case "loading":
      // The document is still loading.
      break;
    case "interactive":
      // The document has finished loading. We can now access the DOM elements.
      break;
    case "complete":
      // The document and all sub-resources have finished loading.
      myFunc();
      break;
  }
}, false);

Upvotes: 3

Related Questions