Internal JavaScript
HTML Document allows JavaScript programs to be inserted in a <script>
tag. The <script>
tag is placed just before the closing <body/>
tag. This allows the HTML parser to load all HTML content first before loading the JavaScript program.
The <script>
tag can also be placed just before the closing <head/>
, but it is a bad practice because the <script>
tag slows down the display of HTML contents.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Internal JavaScript</title>
</head>
<body>
<p>This is the paragraph</p>
<script>
console.log('Hello World!')
</script>
</body>
</html>
External JavaScript
The src
attribute in the <script>
tag links an HTML document to an external JavaScript file.
JavaScript programs can also be placed in an external file. When the same JavaScript code is needed on different web pages, external scripts are the best option.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Internal JavaScript</title>
</head>
<body>
<p>This is the paragraph</p>
<script src='index.js'></script>
</body>
</html>
JavaScript programs can be written in an external or separate file.
script.js
console.log("Hello World!");
Alternatively, the <script>
tag can be placed just before the closing </head>
tag but including the defer
attribute in it.
script.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External JavaScript</title>
<script src='index.js' defer></script>
</head>
<body>
<p>This is the paragraph</p>
</body>
</html>
The
defer
attribute makes sure the HTML Parser loads the HTML contents first before loading the script tag. It is the same as having the<script>
tag before the closing</body>
tag.
Happy Coding!!!
Techstack Media | Hostgator
Techstack article is sponsored by Hostgator.
- A ton of website hosting options
- 99.9% uptime guarantee
- Free SSL certificate
- Easy WordPress installs
- A free domain for a year
Top comments (5)
Didn't know about defer. Awesome!
Yes! You can also use async attribute instead... for unrelated script load...
Yes! You can also use async attribute instead... for unrelated script load...
Buddy, can you tell me the name of the font used in the cover photo?
It is Gidole