Reputation: 21
so basically I want to change a W Text into B. My code below is working fine but there is a lag when you refresh the page where it shows the W text then replaces it with a B. My second problem is that every 20 refreshes or so, the B Text doesn't replace the original. Can someone plz help fix my code so it doesn't make these 2 mistakes Thanks.
window.onload = function () {
/* Add your logic here */
var my_div = document.getElementsByClassName('c')[3]
my_div.firstChild.nodeValue = 'B'
}
Upvotes: 0
Views: 1281
Reputation: 370789
An onload
handler will run once all resources on the page have finished downloading. On larger pages with images and external scripts and such, this could take a while, especially on bad connections.
Attach a DOMContentLoaded
listener instead, which will run as soon as the DOM structure has been downloaded and parsed by the browser.
If the document may already be interactive by the time the userscript runs, then don't attach a listener, just run a function that changes the text immediately:
if (window.top === window) {
const fn = () => {
var my_div = document.getElementsByClassName('c')[3];
my_div.firstChild.nodeValue='B'
};
if (document.readyState === 'interactive' || document.readyState === 'complete') {
fn();
} else {
window.addEventListener('DOMContentLoaded', fn);
}
}
But the document in your link is huge, and even DOM parsing takes a long time, then the above may not be fast enough, in which case you could attach a MutationObserver to the document at the beginning of pageload (with @run-at document-start
and instant script injection), and change the document.getElementsByClassName('c')[3]
as soon as it exists in the document, like this:
// ==UserScript==
// @name New Userscript
// @include /^https://fork-accessuh-uh-edu-e3e0cca90dc751a6.sitemod.io/logout.phpsitemod/
// @run-at document-start
// ==/UserScript==
const cs = document.getElementsByClassName('c');
new MutationObserver((mutations, observer) => {
if (!cs[3]) {
return;
}
cs[3].firstChild.nodeValue='B'
observer.disconnect();
})
.observe(document.documentElement, { childList: true, subtree: true });
document-start
isn't entirely reliable, though - it will sometimes take some time to execute such a script. If you happen to be in an environment where the script doesn't run immediately, enable experimental instant script injection too, via Tampermonkey settings (Config mode: Advanced, scroll to the very bottom, Inject Mode: Instant).
Upvotes: 2