HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

HTML Scripts

HTML is a markup language. It provides the structure of your page, but it is inherently static. It cannot do math, it cannot react to a user swiping the screen, and it cannot fetch new data from a server in the background.

To add logic, interactivity, and true behavior to a webpage, we must use a programming language called JavaScript. To connect JavaScript to our HTML document, we use the <script> tag.


Writing Inline JavaScript

The simplest way to execute JavaScript is to write the code directly between an opening <script> and a closing </script> tag.

<!-- HTML Element -->
<p id="demo-text">This text will change magically!</p>

<!-- JavaScript Engine -->
<script>
  // This code grabs the paragraph above and changes the text inside it
  document.getElementById("demo-text").innerHTML = "Hello from JavaScript!";
</script>

Awaiting JavaScript Action...


Linking External JavaScript Files

Just like how we shouldn't cram all our CSS styles directly into our HTML file, writing hundreds of lines of JavaScript inside a <script> tag quickly becomes unmanageable.

Best practice is to write your JavaScript in a separate file ending in .js, and then link it to your HTML page using the src attribute.

<!-- We don't write anything between the tags if we use 'src' -->
<script src="calculator.js"></script>
<script src="animations.js"></script>

Where should I put the Script tag?

Historically, placing the <script> tag was a bit of a balancing act.

If you put it in the <head>, the browser stops rendering the visual page to download the script, which makes your site feel slow to the user. If you put it at the very bottom of the <body> just before the closing tag, the visual layout loads fast, but the buttons won't work immediately.

Modern HTML solves this with two powerful attributes: defer and async.

The 'defer' Attribute (Recommended)

Placing your script tag in the <head> with the defer attribute is currently the industry standard. It tells the browser: "Download this heavy file in the background while you build the visual HTML. But wait until the entire HTML page is completely finished building before you actually execute the code."

<head>
  <title>Fast Website</title>
  <script src="heavy-code.js" defer></script>
</head>

The <noscript> Fallback

While extremely rare today, it is possible for users to manually disable JavaScript in their browser settings (usually for extreme privacy or security reasons). If your website heavily relies on JavaScript to function, it will appear broken to these users.

The <noscript> tag displays a custom HTML message only to users who have JavaScript disabled. If JavaScript is running normally, this tag remains completely invisible.

<noscript>
  <div style="background: red; color: white;">
    Critical Error: Our checkout system requires JavaScript to process your payment! Please enable it to continue.
  </div>
</noscript>