I'm learning Greasemonkey with the hopes of making some improvements to a webpage.
I think I have a good grasp of JavaScript, but I don't understand at what point in the rendering of the document the Greasemonkey user script is executed.
For instance, what if there is JavaScript natively inside the document that inserts some elements to the page. I want my Greasemonkey script to run only after that JS completes.
Let's say this is the document that I'm trying to modify with Greasemonkey
<html>
<script>
//insert a button with id="mybutton"
</script>
</html>
I want the <script>
code to complete before my Greasemonkey script is run, because I want to alter its background color.
Greasemonkey runs at the DOMContentLoaded event by default. This means that everything will be in the page except for possibly large images and stuff added by some javascripts (scripts that fire on the load
event or that AJAX-in content).
If you want to wait until even large media has loaded and "onload" scripts have run, use:
window.addEventListener ("load", Greasemonkey_main, false);
function Greasemonkey_main () {
//***** PUT YOUR GREASEMONKEY CODE HERE.
}
Do not use unsafeWindow.onload = function(){ ... }
or window.onload = function() { /* logic here */ }
as others have suggested. These are not only poor practice/won't work in GM, but the unsafeWindow
is an unnecessary security risk in this case.
Since you indicated that the node you care about is added by javascript, waiting for the load
event will often not work. JS can add, remove or edit nodes at any time.
The best approach in cases like these is to poll for the element you are interested in ("#mybutton"
). See this answer to "Fire Greasemonkey script on AJAX request".