I'd like my Chrome extension to insert some text in spans which are constantly updated as you scroll. On this page, I can get all the elements I need with this code:
var agoEls = [...document.querySelectorAll("#metadata-line span:nth-child(4)")];
How do I run the code so that it starts working after the first span item appears?
How to get new elements that appear after the page scrolls and run code for them too as they appear?
I tried MutationObserver.observe()
, but I don't know how best to use it in this case. It seems impossible to use it with high performance. I can wait for a body with little performance overhead:
function waitForBody() {
return new Promise(resolve => {
if (document.documentElement.getElementsByTagName("body")) {
return resolve(document.documentElement.getElementsByTagName("body"));
}
const observer = new MutationObserver(mutations => {
if (document.documentElement.getElementsByTagName("body")) {
resolve(document.documentElement.getElementsByTagName("body"));
observer.disconnect();
}
});
observer.observe(document.documentElement);
});
}
waitForBody().then((elm) => {
console.log('Element is ready');
});
But then, as suggested here, I have to use subtree: true
and collect all changes for all elements in the whole giant tree:
Maybe I'm doing something wrong and there's a better way?