1

I'm working on a script (extension) that selects an HTML tag and does some stuff to it. However, this HTML tag will dynamically load up on the page at some given time, and I want to detect it as soon as it loads. Currently I am polling the html page in a while loop (checking for undefined) but it is lagging the page a lot. Is there a workaround?

$(document).ready(function() {
  // some code
  var sizesList=document.getElementsByClassName("exp-pdp-size-dropdown-container nsg-form--drop-down--option-container selectBox-options nsg-form--drop-down exp-pdp-size-dropdown exp-pdp-dropdown two-column-dropdown selectBox-dropdown-menu")[0];
  while(typeof(sizesList) == 'undefined') {
    setTimeout(function() {}, 700)
    sizesList=document.getElementsByClassName("exp-pdp-size-dropdown-container nsg-form--drop-down--option-container selectBox-options nsg-form--drop-down exp-pdp-size-dropdown exp-pdp-dropdown two-column-dropdown selectBox-dropdown-menu")[0];
  }
// some more code
}

I'm testing it on this webpage.

JC1
  • 849
  • 13
  • 25
  • 1
    That while loop probably completely locks up. It might be nicer to have a function that calls setTimeout on itself until that element appears. – Shadow Nov 20 '17 at 02:08

1 Answers1

0

The page is lagging because you're executing sizesList=document.getElementsByClassName(... continuously. The setTimeout is asynchronous, so it won't do anything.

To poll every 700ms like you expect, you should consider setInterval:

setInterval(function() {
    if(typeof(sizesList) == 'undefined')
    sizesList=document.getElementsBy(...
}, 700)
frozen
  • 2,114
  • 14
  • 33
  • Thanks! So if my variable becomes defined, how would I exit the interval and carry on with the rest of the code? – JC1 Nov 20 '17 at 02:13
  • Yeah! See https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript – frozen Nov 20 '17 at 04:46