top of page

Where to place JavaScript

JavaScript can be added to the webpage in a couple of different ways.

The different ways have it's benefits and disadvantages. 

In an external file

Write your script in a file and give it an .js extention. Example: simpleScript.js. 

To use the external script in the webpage, you have to put the name of the file in the src (source) attribute in the <script> tag

You are free to place the script tag with the reference to your script where you want in the webpage. It can be in the <head> or <body> tag. The advantage of writing scripts in own files is that you get separation between the HTML and the script. In large webpages this helps to keep control and a clean(er) code base.

You can refer to the script as shown above, where it is a file located in the same folder as the HTML file. Or you can refer to it from another folder like this:

And last, you can refer to it from another URL, like this:

In the <head> tag

Place your JavaScript script inside the <head> </head> tag.

In the <body> tag

Place your JavaScript script inside the <body> </body> tag.

The script will run when you press the button.

You can place the script anywhere inside the <body> </body> tag, but placing it at the bottom will increase the speed of rending the page. This is because it takes time to interpret the script and it will slow down the rending of the page if it's presented higher up in the page.

©2022 - 2024 by JavaScript Schools.

bottom of page