(click anywhere to close)
OPEN MENU

[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.

Internal

Simply write all your code as the content of the <script> element.

<script>
	/* JavaScript Code Here */
</script>

External

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>

Placement

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.

Execution

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!

CONTINUE WITH THIS COURSE
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)