JavaScript location in HTML File

There is flexibility in providing JavaScript code anywhere in an HTML document. However, the most preferred ways to include JavaScript in an HTML file.

There is flexibility in providing JavaScript code anywhere in an HTML document. However, the most preferred ways to include JavaScript in an HTML file are:

  1. Script in the area .
  2. Script in the area .
  3. Script in the area . and .
  4. Script in the peripheral file and then include in the area .

In the next section, we will see how we can put JavaScript in an HTML file in different ways:

JavaScript in the area .

If you want to have a script run on some event, such as when the user enters somewhere, then you will put that script in the Head as follows:

  type = "text/javascript" >   type = "button" onclick = " sayHello () " value = "Xin chao!" /> 

Execute the above code to see the result.

JavaScript in the area .

If you need a script to run when the page loads so that the script creates content in the page, then the script should be part of the document. In this case, you will not have any functions defined by using JavaScript. See the following code:

  type = "text/javascript" >  
 This is web page body 

This code will produce the following result:

 Hello World 
This is web page body

JavaScript in the area and

You can place JavaScript code in the area and as follows

  type = "text/javascript" >   type = "text/javascript" >   type = "button" onclick = " sayHello () " value = "Xin chao!" /> 

Execute the above code to see the result.

JavaScript in the peripheral file

When you start working more extensively with JavaScript, you will find that there are cases where you are reusing JavaScript code uniformly across multiple pages of a site.

You are not limited to maintaining consistent code in multiple HTML files. The script tag provides a technique that allows you to save JavaScript in an external file and then include it in your HTML files.

Here is an example to show how you can include a peripheral JavaScript file in HTML code using its script tag and src attribute.

  type = "text/javascript" src = "filename.js" > .. 

To use JavaScript from an external source file, you need to write all your JavaScript source code in a single text file with the ".js" extension and then include that file as above.

For example, you can keep the following content in filename.js and then you can use the sayHello function in the HTML file after including this filename.js.

 function sayHello () { alert ( "Hello World" ) } 

According to Tutorialspoint

Previous post: Enable JavaScript in browsers

Next article: Turning in JavaScript

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile