(click anywhere to close)

[JavaScript] Including with HTML

category: Website | course: JavaScript | difficulty:

JavaScript can be written within the HTML page itself (internal), or in a separate file that you link to (external). Either way, the existence of JS is signalled with the <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 <script> element.

	/* JavaScript Code Here */


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 src=”linktofile.js”

<script src="/path/to/file.js"></script>


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!

Do you like my tutorials?
To keep this site running, donate some motivational food!
Chocolate Milk