coding180 icon
Coding180
Places to put JavaScript  in the page

Places to put JavaScript in the page

Home > Tutorials > JavaScript > Getting Started


We can place JavaScript code anywhere in the HTML file, but we generally place it in the head or body of the web page.


Placed in the <head> section
The most common way is to place a <script> element in the head section of the page, and the browser will execute this code when parsing the head section, and then parse the rest of the page.


The JavaScript code placed in the <body> part
will be executed when the statement is read by the web page.

javascript insert head and body

Note:  As a scripting language, JavaScript can be placed anywhere in the HTML page, but the browser interprets HTML in order, so the previous script is executed first. 

JavaScript initialization must be placed in the head, because the initialization is required to be done in advance (such as setting CSS for the page body, etc.); and if the function is executed through an event call, there is no requirement for the location.

Task - Exercise 4

Let's give it a try and write JS code in different locations:

1. Enter on line 7 document.write("I love");

2. Enter on line 12

document.write("javascript");

Now run the program and see the results on your browser!

Task Code

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS code location</title>
<script type="text/javascript">
  
</script>
</head>
<body>
<script type="text/javascript">
 
</script>
</body>
</html>

 


user

Robort Gabriel

Lagos, Nigeria

Freelance Web Developer, Native Android Developer, and Coding Tutor.

Skills
  • UI / UX
  • JavaScript
  • Python
  • PHP
  • Kotlin
  • Java
  • Bootrap
  • Android
  • Laravel