Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.onload not working for me?

Tags:

javascript

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.

like image 962
prk Avatar asked Sep 23 '13 13:09

prk


2 Answers

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...

like image 186
Abraham Avatar answered Sep 21 '22 15:09

Abraham


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.

like image 44
Niet the Dark Absol Avatar answered Sep 20 '22 15:09

Niet the Dark Absol