I\'m writing a Greasemonkey user script, and want the specific code to execute when the page completely finishes loading since it returns a div count that I want to be displ
Brock's answer is good, but I'd like to offer another solution to the AJAX problem that is more modern and elegant. Since his script also uses setInterval()
to check periodically (300ms), it can't respond instantly.
If you need to respond immediately, you can use MutationObserver()
to listen for DOM changes and respond to them as soon as the element is created
(new MutationObserver(check)).observe(document, {childList: true, subtree: true});
function check(changes, observer) {
if(document.querySelector('#mySelector')) {
observer.disconnect();
// code
}
}
Though since check()
fires on every single DOM change, this may be slow if the DOM changes very often or your condition takes a long time to evaluate.
Another use case is if you're not looking for any specific element, but just waiting for the page to stop changing. You can combine this with setTimeout()
to wait for that too.
var observer = new MutationObserver(resetTimer);
var timer = setTimeout(action, 3000, observer); // wait for the page to stay still for 3 seconds
observer.observe(document, {childList: true, subtree: true});
function resetTimer(changes, observer) {
clearTimeout(timer);
timer = setTimeout(action, 3000, observer);
}
function action(o) {
o.disconnect();
// code
}
This method is so versatile, you can listen for attribute and text changes as well. Just set attributes
and characterData
to true
in the options
observer.observe(document, {childList: true, attributes: true, characterData: true, subtree: true});