404 Not Found

404 Not Found


nginx

Getting Started with JavaScript

Adding JavaScript to your web page is easier than you might think — there are three ways to do it, from quick-and-dirty to production-ready.

Three Ways to Add JavaScript

1. Inline (onclick attribute)

Write JS code directly in an HTML element's event attribute, like onclick="...".

This is the simplest approach, but don't use it in real projects — mixing HTML and JS together makes maintenance a nightmare.

2. Internal (<script> tag)

Insert a <script> tag in your HTML file and write JS code inside it. This works well for small pages and is the most common approach during learning and testing.

The <script> tag can go in <head> or <body>, but placing it right before </body> is recommended so it doesn't block page rendering.

3. External (.js file)

Write your JS code in a separate .js file and include it with <script src="xxx.js"></script>. This is the standard practice for real projects — it separates concerns, enables reuse, and lets the browser cache the file for faster loading.

Example: Inline JavaScript

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JS Intro - Inline</title>
  <style>
    body { font-family: Arial, sans-serif; text-align: center; margin-top: 80px; }
    #msg { font-size: 22px; color: #333; }
    button { padding: 10px 24px; font-size: 16px; border: none; border-radius: 6px; background: #FF9800; color: #fff; cursor: pointer; }
    button:hover { background: #F57C00; }
  </style>
</head>
<body>
  <p id="msg">Click the button below</p>
  <button onclick="document.getElementById('msg').textContent='Inline JS executed!'; document.getElementById('msg').style.color='#FF9800';">Click Me</button>
  <p style="margin-top:30px; color:#999; font-size:14px;">👆 This JS is written directly in the onclick attribute</p>
</body>
</html>
▶ Try it Yourself

Example: Internal JavaScript

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JS Intro - Internal</title>
  <style>
    body { font-family: Arial, sans-serif; text-align: center; margin-top: 60px; }
    .box { display: inline-block; width: 150px; height: 150px; background: #9C27B0; border-radius: 12px; transition: all 0.4s; line-height: 150px; color: #fff; font-size: 20px; }
    .box.round { border-radius: 50%; }
    button { display: inline-block; margin: 20px 8px; padding: 10px 24px; font-size: 16px; border: none; border-radius: 6px; cursor: pointer; color: #fff; }
    #toggleBtn { background: #9C27B0; }
    #resetBtn { background: #999; }
  </style>
</head>
<body>
  <div class="box" id="shapeBox">Square</div>
  <br>
  <button id="toggleBtn">Toggle Shape</button>
  <button id="resetBtn">Reset</button>

  <script>
    var box = document.getElementById("shapeBox");
    var isRound = false;
    document.getElementById("toggleBtn").onclick = function() {
      isRound = !isRound;
      if (isRound) {
        box.classList.add("round");
        box.textContent = "Circle";
      } else {
        box.classList.remove("round");
        box.textContent = "Square";
      }
    };
    document.getElementById("resetBtn").onclick = function() {
      isRound = false;
      box.classList.remove("round");
      box.textContent = "Square";
    };
  </script>
</body>
</html>
▶ Try it Yourself

Example: External JavaScript

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JS Intro - External</title>
  <style>
    body { font-family: Arial, sans-serif; text-align: center; margin-top: 60px; }
    #counter { font-size: 48px; font-weight: bold; color: #2196F3; }
    button { padding: 10px 24px; font-size: 18px; border: none; border-radius: 6px; cursor: pointer; color: #fff; margin: 4px; }
    #addBtn { background: #4CAF50; }
    #subBtn { background: #f44336; }
    #resetCount { background: #999; }
  </style>
</head>
<body>
  <h2>Counter</h2>
  <p id="counter">0</p>
  <button id="addBtn">+1</button>
  <button id="subBtn">-1</button>
  <button id="resetCount">Reset</button>

  <!-- In a real project, the JS below should be saved in a separate counter.js file -->
  <!-- <script src="counter.js"></script> -->
  <!-- For demo purposes, we use an internal script here -->
  <script>
    var count = 0;
    var counterEl = document.getElementById("counter");
    document.getElementById("addBtn").onclick = function() {
      count++;
      counterEl.textContent = count;
    };
    document.getElementById("subBtn").onclick = function() {
      count--;
      counterEl.textContent = count;
    };
    document.getElementById("resetCount").onclick = function() {
      count = 0;
      counterEl.textContent = count;
    };
  </script>
</body>
</html>
▶ Try it Yourself

If you're using VS Code (highly recommended), these two extensions are all you need:

Running JS in Chrome DevTools

Press F12 to open DevTools, switch to the Console panel, and you can type JS code directly and press Enter to run it. This is the fastest way to experiment — test any code snippet without creating an HTML file.

Tip: Press the ↑ key in the Console to recall your previous command, saving you from retyping.

The defer and async Attributes on script Tags

When a <script> tag is in the <head>, the browser pauses HTML parsing to download and execute the JS first — which can make the page feel stuck. The defer and async attributes solve this:

Attribute Behavior
None Download and execute immediately, blocks HTML parsing
defer Download in background, execute after HTML is fully parsed (in order)
async Download in background, execute as soon as downloaded (order not guaranteed)

Best practice: adding defer to external JS files is the safest choice — <script src="app.js" defer></script>.


📖 Summary

  1. Three ways to add JS: inline onclick (not recommended), internal <script> (great for learning), external .js file (industry standard)
  2. Place <script> tags right before </body> to avoid blocking page rendering
  3. Use the defer attribute on external JS files — no blocking and guaranteed execution order
  4. Chrome's F12 Console is the fastest JS playground
  5. VS Code + Live Server + ESLint is the standard front-end toolkit
  6. Inline JS is convenient but tightly couples HTML and JS — build the habit of separation early

❓ FAQ

Q What's the difference between putting <script> in the head vs. at the bottom of body?
A In the head, the browser stops to download and execute the script — the page is still blank at that point. At the bottom of body, the page renders first so users don't experience a "freeze." It's like serving food before telling jokes — don't keep your guests hungry.
Q Should I use defer or async?
A Use defer in most cases. It guarantees scripts execute in order and only after the HTML is fully parsed, so DOM elements are always available. async is better for standalone analytics scripts (like Google Analytics) that don't depend on other scripts or the DOM.
Q How many <script> tags can a page have?
A As many as you want — there's no limit. But in practice, try to consolidate into a few external files to reduce HTTP requests.

📝 Exercises

  1. Beginner: Create an HTML page with an internal <script> that shows an alert saying "Welcome to JavaScript!" when the page loads (hint: use alert()).
  2. Intermediate: Create an HTML page and a separate main.js file. Include the JS file with <script src="main.js" defer></script> and implement a button that changes the page background color.
  3. Challenge: Create a page with three buttons, each representing one of the three inclusion methods (inline, internal, external). When any button is clicked, display "This JS was loaded via XXX method" on the page, using different colors to distinguish them.
100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏