<script> element. I recommend always writing your JS in an external file, for two reasons: it is saved (cached) by the user’s browser, and the same code can easily be re-used across multiple files.
Simply write all your code as the content of the
First, write all your code in a separate text file, and save it with the extension
.js. To link to it, leave the
<script> element empty, and include the attribute
Theoretically, you can place this tag anywhere within your document. But, the cleanest method is placing it somewhere in the
<head> tag. Not only does it keep your body clean and organized, it also ensures the script is loaded before the rest of the webpage, which minimizes the chance of running into problems.
Of course, because scripts are essentially just HTML tags inside the web page, you can include as many as you like.
If you place your code within the body, it is automatically executed when the page is loading that script tag. If you use an external file, you’ll need to call whatever part you want executed from the HTML document, either automatically or when the user performs a certain action. We’ll soon see how to do this. Remember this, if you’re ever wondering why nothing’s happening!