Menu Close


JavaScript: script

The JavaScript computer language is used to create scripts rather than large and monolithic applications. Usually a script is part of a HTML web page but can also be a separate file. 

Where to put the script?

We can use tags: <script> JavaScript Code </script> to mark a script into HTML pages. One HTML page can contain many scripts. Each script must be enclosed into tags.

Default scripting language for web pages is JavaScript but it is possible to use other computer languages in HTML web pages using the tag <script>.

Script location in <head> or <body>

In HTML we nest one tag in other tag. The <script> can be nested in the <head> tag into HTML pages or <body> tag. A script can modify HTML elements only after they are defined. So the script location is important. If you define the script earlier it will not have access to all page elements.

Note: Web developers prefer to implement JavaScript in the <body> region of HTML. This is to allow a faster rendering of the page. JavaScript must be compiled and is better to compile the script after the page is loaded.


In this example JavaScript is stored in <head> element of HTML.


In this example JavaScript is located in the <body>

External Scripts

We can create JavaScript files with extension js that are loaded in HTML pages using tag script with attribute src like this:


In this example  JavaScript myFunction is hooked to an click event of the button. When user press the button the function is executed.

Externa file: “myScript.js” contain the declaration for function myFunction().


Placing JavaScripts in external files has some advantages:

  • It separates HTML and code so HTML is smaller
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads
  • External JavaScript functions can be reused in many HTML pages

Read next: Functions