Home / Web / Where to place JavaScript code in a webpage?
javascript location

Where to place JavaScript code in a webpage?

There are three ways to place JavaScript code in a webpage that are

  • Inside the head tag
  • Within the body tag
  • In an external file

The location choice of head or body is very simple. If you want to have runa script on some event, such as when a user clicks somewhere, then you will place that script in the head.

Examples

  1. Script inside the head tag:

<html>

<head>

<script type=”text/JavaScript”>

<!–

function popup() {

alert(“Hello Allhelpservices”)

}

//–>

</script>

</head>

<body>

<input type=”button” onclick=”popup()” value=”popup”>

</body>

</html>

 

  1. Script within the body tag

<html>

<body>

<script type=”text/JavaScript”>

<!–

document.write(“Hello Allhelpservices !”)

//–>

</script>

</body>

</html>

 

Output of above code should be:

Hello Allhelpservices !

  1. JavaScript adding using external file

Using an external file is relatively painless. The file you are importing must be valid JavaScript and file contains only JavaScript code. The file must have extension “.js”. Lastly, you must know the location of the file.

Let us consider we have a file “helpjs.js” that contains a Hello Allhelpservices alert function. Also, let us assume that the file is the same directory as the HTML file we are going using. To import the file you would do the following in your HTML code.

helpjs.js file contains :

function popup() {

alert(“Hello World”)

}

 

HTML Code:

<html>

<head>

<script src=”myjs.js”>

</script>

</head>

<body>

<input type=”button” onclick=”popup()” value=”Click Here!”>

</body>

</html>

 

Output will be show alert box after clicking on button “Click Here!”

In this way you can use or place JavaScript code in a webpage.

Note: JavaScript external file are placed before closing body tag or place within footer area, it may help to reduced load time of webpage.

For understanding what is mean by JavaScript “CLICK HERE!

About Helpservices

About This site (allhelpservices.com) is dedicated to helping other bloggers learn the skills of blogging, wordpress, education, technology, social media sharing , SEO, Electronics, Earn Money From Blogging, Web hosting and web share their own experiences and promote the blogging medium. We started Allhelpservices in August 2015 mainly because we wanted to keep a record of what we wear learning from development and because we wanted to connect with other learners.

Check Also

style sheet

What are ways of inserting a style sheet?

Cascading Style Sheets (CSS) describe how documents are presented on screens, in print, or perhaps ...

Leave a Reply