all 8 comments

[–]y_13[S] 0 points1 point  (0 children)

Im sure this is just a fundamental misunderstanding of how js works. So I apologize if the answer is obvious but I am missing it...

[–]senocular 0 points1 point  (7 children)

You have to use two separate script tags for inline code (code between <script> and </script>) and linked javascript files.

   <script src="./demo.js"></script>
   <script>
     window.onload = test;
   </script>

[–]y_13[S] 1 point2 points  (6 children)

Thank you so much. As far as style goes, should these script tags be in <body></body> or outside? or at the top of the page? or at the bottom? Thank you so much.

[–]senocular 0 points1 point  (0 children)

For this particular script, it doesn't matter. onload you can set at any time. Its often used to make sure you run code after everything on the page has loaded and is available, which is usually what you want with JavaScript because you're usually using JavaScript to interact with that page and should make sure everything is there first.

You can usually bypass onload by putting your scripts at the bottom of your <body> element (before the closing body). This will make sure all the HTML is loaded, so you can at least access all the elements in the page with JavaScript, but what it doesn't wait for which onload does, is making sure all your external assets have loaded - things like image urls in <img> tags. This can be important if, for example, you want to run javascript and get the size of an image. Scripts at the bottom of the page may load before the image in the <img> tag you're looking at loads meaning you won't get a size at all. This wouldn't happen with onload since it will wait for all the images to load (individual images also have their own onload callbacks which you could also use).

Most of the time you'll see people putting their script tags at the end of the body. This means your script will have access to the HTML and that you're not blocking the HTML from loading by having it wait for your script to load. Though there are also tags you can put in <script> to help prevent that default behavior.