How to check if a document is ready in JavaScript?

I am developing a simulator to simulate user actions on a web page. In the particular case of the page that clicked on each change in the content of the page, there are several buttons. I programmatically click on each button and then want to extract the new content added to the page. If you look at:

http://www.elementbars.com/Build-a-Bar-Service.aspx#

you can find an example.

My code looks something like this:


for (var int i=0; i< buttonArray.length; i++){ // buttonArray is the array of buttons triggerClickEvent(buttonArray[i]); extractNewContent(); } function triggerClickEvent (clickableElement) { jQuery(clickableElement).trigger('click'); } 

Both triggerClickEvent and extractNewContent work correctly, but the problem is that after the click event is fired, the JavaScript engine has to wait a while to make sure the new content is added, but it does not behave as expected. For example, I noticed that all buttons are pressed, but extractNewContent extracts the content for the first button, which means that these two functions do not work synchronously. I used the setTimeout function, but since it does not block execution, it therefore cannot solve the problem. I also used functions that check the status of the document, but do not work.

I would be grateful if you could help me.

Thanks.

+4
source share
3 answers

The easiest way to do this is through tools like jQuery. Something like that:

 jQuery(document).ready(function() { ... }); 

or more concise

 jQuery(function() { }); 

Part of the problem is that "ready-made" is not standardized in browsers. To do this, use tools such as jQuery.

0
source

You can pass parameters to run the function, one of which in our case will be the extractBueNewContent function. And call this function after all the changes have been made in the click event handler. So the handler will be

 $(clickableElement).on('click', function(event, callback){ ... all DOM modifications goes here ... if(typeof callback === "function") callback(); } 

and then call it using extractNewContent as a parameter

 $(clickableElement).trigger('click',extractNewContent); 
0
source

The following code works:

 for (var int i=0; i< buttonArray.length; i++){ // buttonArray is the array of buttons triggerClickEvent(buttonArray[i]); alert('balalalala'); // if you remove this, it won't work. extractNewContent(); } function triggerClickEvent (clickableElement) { jQuery(clickableElement).trigger('click'); } 
0
source

Source: https://habr.com/ru/post/1493440/


All Articles