javascriptonloadexternal-js

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";
}

Solution

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