Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Nhúng JavaScript vào file HTML


Có 2 cách chính nhúng JS vào HTML:

  • Inline: Viết thẳng trong thẻ <script>.
  • External: File .js riêng, nhúng bằng <script src="...">. Nên thêm defer (chạy sau khi HTML parse xong) hoặc async (tải song song, chạy ngay khi xong).

Ví dụ

File HTML nhúng inline + external script.js:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Nhúng JS vào HTML</title>
  <script src="script.js" defer></script>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 18px; font-weight: 500; color: rebeccapurple; }
  </style>
</head>
<body>
  <h1>Nhúng JavaScript vào file HTML</h1>
  <div class="result"></div>
  <script>
    document.querySelector(".result").innerHTML += "Inline JS đã tải<br>";
  </script>
</body>
</html>

script.js

document.querySelector('.result').innerHTML += 'External JS đã tải';

Kết quả

Cả hai dòng đều hiển thị. defer đảm bảo external script chạy sau khi DOM sẵn sàng (trước DOMContentLoaded).

Khuyến nghị: Luôn dùng external file + defer cho code production. Inline chỉ cho script rất nhỏ, critical.