JavaScript-HTML Link

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article


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.

Internal JavaScript

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>

Edit on Stackblitz


image.png


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>External 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='script.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.

Edit on Stackblitz

Happy Coding!!!


Buy me a Coffee


Techstack | 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

No Comments Yet