r/GreaseMonkey • u/TheRedParduz • Jul 21 '26
TAmpermonkey: How to start the script when this page is fully loaded?
I'm trying to make a script on this page:
https://www.meteoam.it/it/meteo-citta/bologna
(it is a weather forecast page from the italian military air force)
I want to add a style to each of the "slots" of the forecast, but the scripts starts before that page section is loaded, so the elements the scripts query for are still not existent; I don't know what should I do.
Could someone help me? I just need to know how to execute it at the right time.
3
Upvotes
2
u/AyrA_ch Jul 21 '26
Try
// @run-at document-idleIf that is still too early, it means the content is dynamically loaded after the page itself, in which case you need something like a mutation observer to detect the moment the required content is inserted.
1
u/_1Zen_ Jul 21 '26
If you only want to apply CSS, the best option is to create a userstyle. If you need to use a userscript, you can use a
MutationObserverto detect elements that are added to the page dynamically.Simple example:
This approach may detect the same element multiple times. To avoid that, use a selector that skips elements that have already been processed:
If your script is simple and performs little DOM manipulation, this approach is usually enough. However, if it performs heavier DOM operations, it's more efficient to iterate over each mutation's
addedNodesand process only the newly added elements: