Blog
JavaScript script tag
JavaScript script tag
The <script> tag in JavaScript is used to embed or reference scripts in an HTML document. It tells the browser that the enclosed code is JavaScript and should be executed.
JavaScript is implemented by adding <script>… </script> tag within the HTML tag in a web page. The <script> tag instructs the browser about the JavaScript code and to process the script separately.
<script> tag can be inserted within the web page in:
- head section
- body section
Basic Syntax
The basic syntax is as follows:
Script in<head> section
<head>
<script....>
//Your JavaScript code goes here
</script>
</head>
Script in <body> section
<body>
<script.....>
// Your JavaScript code goes here
</script>
</body>
<script> tag has the following attributes
language
The language attribute is set to value “JavaScript”, which tells the browser that the scripting language is JavaScript.
type
The type attribute tells the browser that the script is in plain text and the text is organized in the format of a JavaScript. This is for browser information– how to read the JavaScript code.
<script language="JavaScript" type ="text/javascript">
document.write("Hello, world!")
</script>
src
Specifies the external JavaScript file to load.
<script src="script.js"></script>
async
Loads the script asynchronously (doesnât block HTML parsing). Good for independent scripts like ads or analytics.
<script src="analytics.js" async></script>
defer
Loads the script in order, but execution is delayed until the HTML is fully parsed. Great for DOM-related scripts.
<script src="main.js" defer></script>