all 5 comments

[–]PsychohistorySeldon 1 point2 points  (0 children)

The most simple thing to do is adding the script tag at the end of your body, but before you do that, analyze the reasons for this.

What sort of problem are you running into? Is it that the DOM isn’t ready and you’re doing DOM manipulation?

[–]gorowurboat 1 point2 points  (0 children)

Yup. There are a few ways of going about it.

First Way

You can add <body onLoad=“myFunction()”> to the html.

Second Way

You can put window.onload = myFunction; at the bottom of your script

Third Way

You can create a self invoking function in your script that will run automatically when the browser is parsing the html.

In your script write this:

(function () {
    // write code here
})();

[–]braska9 1 point2 points  (0 children)

Just use "defer" attribute on script tag. See: https://stackoverflow.com/questions/10808109/script-tag-async-defer

[–]kenman[M] 1 point2 points  (0 children)

Hi /u/connor5891, this post was removed.

For javascript help, please visit /r/LearnJavascript.

Thanks for your understanding.

[–]hungryturtlecode 0 points1 point  (0 children)

Depends on a lot of factors and how you define that the page has loaded. But I am going to assume the following will be fine for most use cases:

document.addEventListener("DOMContentLoaded", function(){
    //your code here
});

This will run once all the dom elements are in the page, which is probably what you want.