#2 Unknowns in known HTML

August 24th 2024 | 2 min read

179 |  15

Logo

Hello Everyone,
Welcome back to my blog 🙏.
I hope you are all safe and that this blog finds you in good health ️🫶.

Introduction

We know that Scripts can be added to an HTML in two different ways

👉 Internal scripts— Including our script inside the HTML

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body> 
    <button onclick="clickMe()">Click me</button>
</body>
<script>  function clickMe() { console.log('Click Me') }</script>

👉 External scripts — Getting it from external files

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./index.js"></script>
</head>

<body> 
    <button onclick="clickMe()">Click me</button>
</body>

I hope we are clear with this part, Now let’s check on the most commonly used script types

<script type="text/javascript" src="./index.js"></script>

This is similar to the internal one but only we have src and get it from an external file. Here you don’t need to add any event listeners to make your button work and it is just the way you code.

<script type="module src="./index.js"></script>

Module type works in a different way. Modules support imports and exports which we often use in the frameworks.

They have the same-origin policy in-built which means you can’t run the script directly with the file in the browser, you should indeed have a server that runs your code.

error
If you are using VS code, you can live server extension to run the code or you can use http-server.

The module has its own scope and it is detached from the global scope which means you can’t access your button directly instead you need to explicitly add an event listener to your button.

index.html

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./index.js" type="module" defer></script>
</head>

<body> 
    <button id="module">Click me in Module</button><
/body>
// index.js
function clickMeInModule() {
  console.log('Click me in module')
} 

document.getElementById('module').addEventListener('click',
                                                   clickMeInModule)

Here we go, That’s it folks for this short blog.
I hope everyone liked this blog.
If you like it, give it a clap đź‘Ź ,
and share it with your friend.

For more exciting content on Frontend, Please do follow me 🎯.

via GIPHY

Thanks a lot, Everyone 🙏.
Until Next time,
Happy Learning 📖✍️.

Abhishek Kovuri, UI developer