Well I'm simply playing around with a userscript of GreaseMonkey and here's just something simple I attempt to do;
function test() {
document.getElementById('elementhere').innerHTML = 'test';
}
document.onload = test();
It works if I go to the page I want to use it on and do "run" or "reload & run" - but it won't run automatically, which I'm trying to make it do by using document.onload.
What you need is:
window.onload = function () {
// do the work after everything was loaded (DOM, media elements)
}
document.onload it doesn't exist. It works if you at least target some specific element from document for example:
document.querySelector("img").onload = function ()
{// do your thing after 'img' was loaded}
You have other options if you want to execute some code after the DOM is the only element ready without wait for media elements to load like:
Import an async script tag loading the file with the code: You can place this tag wherever you want in DOM and it will not interrupt nothing, will load after the DOM finish to load. you should take a look to MDN documentation about that.
If you take a look again in MDN documentation they will recommend you in section Notes to use DOMContentLoaded and DOMFrameContentLoaded events which can be handling by addEventListener. So, if you do this:
document.addEventListener('DOMContentLoaded', handlerFunc);
Will work for you.
I hope this can be helpful for you...
When you write document.onload = test()
, you are calling the test
function, and assigning its return value to the onload
handler. This is clearly not what you intended.
document.onload = test;
This will assign a reference to the test
function to the onload
handler. When the event fires, that is when your function will be called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With