Rice_Crisp
Rice_Crisp

Reputation: 1261

External javascript window.onload firing early

I have a page that references an external javascript file, and when I tell it run a function onload, it is giving me errors (I assume because it is firing before the page is loaded.) "Cannot set property 'innerHTML' of null"

What do I need to do here to fire run() after the page is loaded?

HTML

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" src="js/test.js"></script>
</head>
<body>
    <div id="test"></div>
</body>
</html>

JS

window.onload = run();

function run() {
    document.getElementById("test").innerHTML = "found it";
}

Upvotes: 0

Views: 752

Answers (2)

Vivin Paliath
Vivin Paliath

Reputation: 95508

It should be:

window.onload = run;

When you do:

window.onload = run();

You're actually running the function called run, and then assigning its return-value (undefined in this case) to window.onload.

This function is running before the page even gets loaded (since you are running it explictly by doing run()), at which time the div with id test doesn't even exist. This is why you're getting the error.

Upvotes: 2

David Hellsing
David Hellsing

Reputation: 108480

Try this instead:

window.onload = run

When you do window.onload = run() you are immediately executing run() and assign whatever is returned to the window.onload property. This is why it’s not working correctly.

Upvotes: 2

Related Questions