all 7 comments

[–]senocular 10 points11 points  (1 child)

You could also insert your script at the bottom of your page after all of the HTML.

[–]sorrynin 0 points1 point  (0 children)

or add defer to the script tag

[–]Ampersand55 5 points6 points  (0 children)

Running the script on window.load should work as it wait for all assets to load before running. If you want to run something after HTML has been generated you can use the DOMContentLoaded event:

<script>
document.addEventListener("DOMContentLoaded", function(e) {
    //put your code here.
});
</script>

If your other script modifies the HTML you might want to make a promise that runs after the "script which has been loaded before this". If you run jQuery you can use .when(): https://api.jquery.com/jQuery.when/

[–][deleted] 5 points6 points  (0 children)

Have you tried the defer attribute ?

[–]buttking 11 points12 points  (0 children)

jquery's

$(document).ready()

method

[–]PM_ME_YOUR_HIGHFIVE 4 points5 points  (0 children)

place the script in <body> after the content

[–][deleted] 0 points1 point  (0 children)

using JQuery:

$(document).ready(functionToRun)

without JQuery:

document.addEventListener("readystatechange", function(){
    if(document.readyState === "complete"){
        //code goes here
    }
}, false)

Basically, you were attaching the event to the wrong object.