🚀 บทนำ HTML5
HTML5 เป็นเวอร์ชันล่าสุดของ HyperText Markup Language ที่ออกแบบมาเพื่อ:
-
เพิ่มความหมายของเนื้อหา (Semantic Web) - ใช้ tag
ที่มีความหมายที่ชัดเจน เช่น
<header>,<article>,<footer>แทน<div>ทั่วไป -
รองรับ multimedia อย่างเป็นทางการ - มี tag
<video>และ<audio>ในตัว ไม่ต้องใช้ Flash player -
ปรับปรุง form validation - มี input types ใหม่ๆ
เช่น
email,date,number -
รองรับ APIs สำหรับ offline, geolocation, storage:
- Geolocation API
- Local Storage
- Service Workers
-
ส่งเสริม responsive web design:
- Meta viewport tag
- CSS media queries
| คุณลักษณะ | ประโยชน์ |
|---|---|
| Semantic tags | SEO ดีขึ้น และโค้ดอ่านง่ายขึ้น |
| Native video/audio | ไม่ต้อง Flash player |
| Canvas & SVG | สร้างกราฟิกและแอนิเมชั่น |
| Form validation | เพิ่มความปลอดภัยและ UX |
| Local storage | เก็บข้อมูลบน browser |
| Responsive | ทำงานได้บน desktop, tablet, mobile |
🏗️ โครงสร้างพื้นฐาน HTML5
DOCTYPE → html → head (meta, title) → body (content)
HTML5 Document Template
เทมเพลตพื้นฐาน HTML5 ที่ถูกต้อง:
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="คำอธิบายเพจ" />
<title>ชื่อของหน้าเว็บ</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<header><h1>ยินดีต้อนรับ</h1></header>
<main><article><p>เนื้อหา...</p></article></main>
<footer><p>© 2024</p></footer>
<script src="script.js"></script>
</body>
</html>
องค์ประกอบ <head> สำคัญ
Meta tags สำหรับ SEO, responsive, social sharing:
<!-- Character encoding -->
<meta charset="UTF-8" />
<!-- Viewport สำหรับ responsive design -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- SEO -->
<meta name="description" content="คำอธิบายเพจสั้นๆ" />
<meta name="keywords" content="html5, web design" />
<!-- Open Graph (Social Media) -->
<meta property="og:title" content="ชื่อเพจ" />
<meta property="og:image" content="url-to-image.jpg" />
<!-- Favicon -->
<link rel="icon" href="favicon.ico" />
🏛️ Semantic Elements
<header>, <nav>, <main>, <article>, <section>, <aside>, <footer>
ประโยชน์:
- ดี: SEO
- ดี: accessibility
- ดี: readability
| Tag | ใช้สำหรับ |
|---|---|
| <header> | ส่วนหัว (ชื่อเพจ, logo, menu) |
| <nav> | เมนูนำทาง |
| <main> | เนื้อหาหลัก (มีแค่ 1 อัน) |
| <article> | บทความ, โพสต์ |
| <section> | ส่วนของหน้า |
| <aside> | เนื้อหารอบข้าง, sidebar |
| <footer> | ส่วนท้าย |
| <figure> | รูป, ไดอะแกรม |
โครงสร้างเพจ Semantic
นี่เป็นตัวอย่างโครงสร้างเพจที่ดี ใช้ semantic elements อย่างถูกต้อง
- <header> ประกอบด้วย navigation
- <main> ส่วนเนื้อหาหลัก
- <article> สำหรับบทความ
- <aside> สำหรับเนื้อหารอบข้าง
- <footer> ส่วนท้าย
<header>
<nav>
<ul>
<li><a href="/">หน้าแรก</a></li>
</ul>
</nav>
</header>
<main>
<article>
<h1>ชื่อบทความ</h1>
<p><time datetime="2024-11-27">27 พฤศจิกายน 2567</time></p>
<p>เนื้อหาบทความ...</p>
</article>
<aside>
<h3>บทความที่เกี่ยวข้อง</h3>
</aside>
</main>
<footer>
<p>© 2024</p>
</footer>
📋 Form Elements
รับข้อมูลผู้ใช้: input types (email, date, number), validation, required, pattern, min/max
Basic Form Structure
<form> → <label> + <input> → <button> (validate client & server)
<form action="submit.php" method="POST">
<label for="name">ชื่อ:</label>
<input type="text" id="name" name="name" required />
<label for="email">อีเมล:</label>
<input type="email" id="email" name="email" required />
<label for="age">อายุ:</label>
<input type="number" id="age" name="age" min="18" max="120" />
<button type="submit">ส่งข้อมูล</button>
</form>
Input Types ใน HTML5
text, email, password, number, date, time, color, file, checkbox, radio (with validation)
| Type | ใช้สำหรับ |
|---|---|
text |
ข้อความปกติ |
email |
อีเมล (มี validation) |
password |
รหัสผ่าน |
number |
ตัวเลข |
range |
Slider |
date |
วันที่ (date picker) |
time |
เวลา |
color |
สี (color picker) |
file |
อัพโหลดไฟล์ |
checkbox |
เลือกหลายตัวเลือก |
radio |
เลือกหนึ่งตัวเลือก |
Form Validation Attributes
required, pattern, min/max, minlength/maxlength, placeholder, disabled, readonly
- required: ฟิลด์ต้องกรอก
- pattern: ต้องจับคู่กับ regex pattern
- min/max: ค่าต่ำสุด/สูงสุด
- minlength/maxlength: ความยาว
- placeholder: ข้อความแสดงตัวอย่าง
- disabled: ปิดใช้งาน
- readonly: ไม่แก้ไขได้
<!-- Required: ต้องกรอก -->
<input type="text" required />
<!-- Pattern: regex validation -->
<input type="text" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" />
<!-- Min/Max: ค่าต่ำสุด/สูงสุด -->
<input type="number" min="1" max="100" />
<!-- MinLength/MaxLength -->
<input type="text" minlength="3" maxlength="20" />
<!-- Placeholder -->
<input type="email" placeholder="example@email.com" />
<!-- Disabled -->
<input type="text" disabled />
<!-- Readonly -->
<input type="text" readonly value="ข้อมูลที่ไม่แก้ไขได้" />
🎬 Media Elements
HTML5 รองรับ audio และ video อย่างเป็นทางการ โดยไม่ต้องใช้ Flash player หรือ plugin อื่น ทำให้ embedd multimedia ได้ง่ายขึ้น:
- <audio>: สำหรับไฟล์เสียง
- <video>: สำหรับไฟล์วิดีโอ
- ทั้งสองรองรับ multiple file formats สำหรับ browser compatibility
Audio Element
Audio element ใช้สำหรับเล่นไฟล์เสียง:
- controls: แสดงปุ่มควบคุม (play, pause, volume)
- autoplay: เล่นอัตโนมัติเมื่อหน้าโหลด (ต้องมี muted)
- muted: ปิดเสียงโดยค่าเริ่มต้น
- loop: เล่นซ้ำ
- <source>: ระบุไฟล์และ MIME type (เพื่อ browser compatibility)
<!-- Audio พื้นฐาน -->
<audio controls>
<source src="music.mp3" type="audio/mpeg" />
<source src="music.ogg" type="audio/ogg" />
เบราว์เซอร์ของคุณไม่รองรับ audio
</audio>
<!-- Audio Autoplay -->
<audio autoplay muted loop>
<source src="background.mp3" type="audio/mpeg" />
</audio>
Video Element
Video element ใช้สำหรับเล่นไฟล์วิดีโอ:
- controls: แสดงปุ่มควบคุม (play, pause, volume, fullscreen)
- width/height: ขนาดวิดีโอ
- poster: รูปพื้นหลังแสดงก่อนเล่น
- autoplay: เล่นอัตโนมัติ (ต้องมี muted)
- muted: ปิดเสียง
- loop: เล่นซ้ำ
- <source>: ระบุไฟล์และ MIME type (รองรับหลาย formats เพื่อ compatibility)
<!-- Video พื้นฐาน -->
<video controls width="600" height="400">
<source src="video.mp4" type="video/mp4" />
<source src="video.webm" type="video/webm" />
เบราว์เซอร์ของคุณไม่รองรับ video
</video>
<!-- Video ที่มี poster -->
<video controls poster="poster.jpg">
<source src="video.mp4" type="video/mp4" />
</video>
<!-- Video Autoplay -->
<video autoplay muted loop>
<source src="background.mp4" type="video/mp4" />
</video>
Media Attributes
Media attributes ใช้ร่วมกับทั้ง <audio> และ <video> เพื่อควบคุมลักษณะการเล่น:
- controls: ระบบควบคุม (required for user control)
- autoplay: เล่นอัตโนมัติ (ต้องมี muted)
- muted: ปิดเสียงโดยค่าเริ่มต้น
- loop: เล่นซ้ำเมื่อจบ
- preload: โหลดล่วงหน้า (none, metadata, auto)
- poster: รูปพื้นหลัง (video only)
| Attribute | ใช้สำหรับ |
|---|---|
controls |
แสดงปุ่มควบคุม |
autoplay |
เล่นอัตโนมัติ (ต้องมี muted) |
muted |
ปิดเสียง |
loop |
เล่นซ้ำ |
preload |
โหลดล่วงหน้า |
poster |
รูปพื้นหลัง (video) |
🎨 Canvas และ SVG
HTML5 มี 2 วิธีหลักสำหรับการวาดกราฟิก:
- Canvas: pixel-based, ใช้ JavaScript เขียนโดยตรง
- SVG: vector-based, DOM elements, scalable
Canvas: Drawing Graphics
Canvas เป็น HTML element ที่ช่วยให้วาดกราฟิกโดยใช้ JavaScript ได้แบบ real-time:
- Pixel-based (raster): เหมาะสำหรับ images, animations
- ต้องใช้ getContext('2d') เพื่อเข้าถึง drawing API
- Drawing methods: fillRect, drawCircle, fillText, drawImage ฯลฯ
- ดี: แอนิเมชั่น, เกม, กราฟิก complex
- ไม่ดี: ไม่ scalable, ไม่ search engine friendly
<!-- Canvas Container -->
<canvas id="myCanvas" width="400" height="300"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// Draw rectangle
ctx.fillStyle = "#FF0000";
ctx.fillRect(20, 20, 100, 100);
// Draw circle
ctx.fillStyle = "#0000FF";
ctx.beginPath();
ctx.arc(200, 150, 50, 0, 2 * Math.PI);
ctx.fill();
// Draw text
ctx.fillStyle = "#000000";
ctx.font = "20px Arial";
ctx.fillText("Hello Canvas", 20, 300);
</script>
SVG: Scalable Vector Graphics
SVG เป็นรูปแบบกราฟิก vector ที่สามารถขยายขนาดได้โดยไม่สูญเสียคุณภาพ:
- Vector-based: เหมาะสำหรับ icons, logos, diagrams
- Scalable: ขยายขนาดได้ไม่มีปัญหา
- DOM elements: สามารถ manipulate ด้วย CSS/JavaScript
- Searchable: content searchable โดย search engines
- Basic shapes: rect, circle, line, text, polygon ฯลฯ
- ดี: ไอคอน, โลโก้, สามารถ manipulate ด้วย JavaScript
<svg width="400" height="300">
<!-- Rectangle -->
<rect x="20" y="20" width="100" height="100"
fill="#FF0000" stroke="#000" stroke-width="2" />
<!-- Circle -->
<circle cx="200" cy="150" r="50"
fill="#0000FF" stroke="#000" stroke-width="2" />
<!-- Line -->
<line x1="0" y1="0" x2="400" y2="300"
stroke="#00FF00" stroke-width="2" />
<!-- Text -->
<text x="20" y="280" font-size="20" fill="#000">
Hello SVG
</text>
</svg>
Canvas vs SVG
ตัวเลือกระหว่าง Canvas และ SVG ขึ้นอยู่กับความต้องการ:
| Canvas | SVG |
|---|---|
| Raster (pixel-based) | Vector (path-based) |
| ละเอียดลงเมื่อ zoom in | ชัดเจนไม่ว่า zoom |
| JavaScript control | DOM manipulation |
| ดี: แอนิเมชั่น, เกม | ดี: ไอคอน, โลโก้ |
| ไม่ search engine friendly | Searchable |
⚙️ Web APIs
Geolocation, Local Storage, Fetch, Notifications, Device APIs
- เข้าถึงตำแหน่งภูมิศาสตร์ของผู้ใช้ (GPS, WiFi)
- เก็บข้อมูล locally บน browser
- ทำ HTTP requests อย่างสมัยใหม่
- ส่ง notifications
- ใช้ fullscreen, battery status, device motion ฯลฯ
Geolocation API
รับตำแหน่งคน (GPS, WiFi)
- navigator.geolocation.getCurrentPosition()
- navigator.geolocation.watchPosition()
- คืนค่า: latitude, longitude, accuracy
<button onclick="getLocation()">รับตำแหน่ง</button>
<p id="result"></p>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
document.getElementById("result").innerHTML =
"ไม่รองรับ Geolocation";
}
}
function showPosition(position) {
const lat = position.coords.latitude;
const lng = position.coords.longitude;
const accuracy = position.coords.accuracy;
document.getElementById("result").innerHTML =
`ละติจูด: ${lat}<br>ลองติจูด: ${lng}`;
}
</script>
Local Storage
เก็บข้อมูล persistent บน browser
- ขนาด: 5-10 MB
- Methods: setItem, getItem, removeItem, clear
- ใช้สำหรับ: preferences, cache, settings
<script>
// Save data
localStorage.setItem("username", "John Doe");
localStorage.setItem("user", JSON.stringify({name: "John", age: 30}));
// Get data
const username = localStorage.getItem("username");
const user = JSON.parse(localStorage.getItem("user"));
// Remove data
localStorage.removeItem("username");
// Clear all
localStorage.clear();
</script>
Fetch API
Modern HTTP requests: GET, POST, PUT, DELETE (ใช้ Promises & async/await)
<script>
// GET request
fetch("https://api.example.com/users")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
// POST request
fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "John",
email: "john@example.com",
}),
})
.then(response => response.json())
.then(data => console.log(data));
// Async/Await
async function fetchUsers() {
try {
const response = await fetch("https://api.example.com/users");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
</script>
Notification API
Notification API ช่วยให้แสดง notifications จากเว็บไซต์:
- ต้องขอ permission จากผู้ใช้
- แสดง notification นอกเว็บไซต์ (เหมือน app notifications)
- Notification.permission: denied, default, granted
- ใช้สำหรับ: alerts, reminders, messages
- ไม่ได้รองรับในทุก browsers/devices
<button onclick="showNotification()">แสดง Notification</button>
<script>
function showNotification() {
if ("Notification" in window) {
if (Notification.permission === "granted") {
new Notification("สวัสดี!", {
body: "นี่คือ notification จากเว็บไซต์",
icon: "icon.png",
});
} else if (Notification.permission !== "denied") {
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
new Notification("สวัสดี!");
}
});
}
}
}
</script>
✨ Best Practices
Best practices ช่วยให้สร้างเว็บไซต์ที่ดี, accessible, secure, และ performant เหล่านี้คือข้อคิดเห็นจากประสบการณ์และ standards ของ industry
1. ใช้ Semantic HTML
ใช้ semantic tags ที่บ่งบอกความหมาย เช่น <header>, <nav>, <article>, <footer> แทนการใช้ <div> ทั่วไป
ประโยชน์:
- SEO ดีขึ้น
- โค้ดอ่านง่ายขึ้น
- Accessibility ดีขึ้น
- Styling ง่ายขึ้น
<div class="header">
<div class="title">
ชื่อเพจ
</div>
</div>
<header>
<h1>ชื่อเพจ</h1>
</header>
2. Accessibility (a11y)
Accessibility ช่วยให้ผู้ใช้ทุกคนสามารถใช้เว็บไซต์ได้ รวมถึงผู้ที่มีปัญหาด้านสายตา การได้ยิน หรือความเคลื่อนไหว:
- Alt text สำหรับรูป (ให้ความหมาย ไม่ใช่แค่ชื่อไฟล์)
- Label สำหรับ form inputs
- Color contrast ให้เพียงพอ
- Keyboard navigation ต้องใช้ได้
- ARIA attributes เมื่อจำเป็น
- Semantic HTML
- Descriptive links ("read more" vs "click here")
<!-- Alt text สำหรับรูป -->
<img src="logo.png" alt="โลโก้บริษัท" />
<!-- Label สำหรับ form -->
<label for="email">อีเมล:</label>
<input type="email" id="email" name="email" />
<!-- ARIA attributes -->
<button aria-label="ปิด menu" onclick="closeMenu()">✕</button>
<!-- Semantic structure -->
<main>
<article>
<h1>ชื่อบทความ</h1>
</article>
</main>
3. Performance
Performance มีผลต่อ user experience และ SEO:
- defer/async สำหรับ JavaScript (defer ส่วนใหญ่, async สำหรับ external)
- Lazy loading สำหรับ images (loading="lazy")
- Specify image dimensions (ป้องกัน layout shift)
- Minify CSS/JavaScript
- Compress images
- ใช้ CDN
- Caching strategy
- Preload สำคัญ resources
<!-- Defer JavaScript loading -->
<script src="script.js" defer></script>
<!-- Async สำหรับ external scripts -->
<script src="analytics.js" async></script>
<!-- Lazy load images -->
<img src="image.jpg" loading="lazy" alt="description" />
<!-- Preload สำคัญ resources -->
<link rel="preload" href="font.woff2" as="font" />
4. Responsive Design
Responsive design ทำให้เว็บไซต์ทำงานได้ดีบน desktop, tablet, mobile:
- Viewport meta tag สำคัญสุด
- Mobile-first approach
- CSS Media queries
- Flexible layouts (Flexbox, Grid)
- Responsive images (<picture> tag, srcset)
- Breakpoints: 480px (mobile), 768px (tablet), 1024px (desktop)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
/* Mobile first */
.container {
width: 100%;
padding: 10px;
}
/* Tablet */
@media (min-width: 768px) {
.container {
width: 750px;
margin: 0 auto;
}
}
/* Desktop */
@media (min-width: 1024px) {
.container {
width: 960px;
}
}
</style>
</head>
<body>
<div class="container"></div>
</body>
</html>
5. SEO Best Practices
ช่วยให้เว็บไซต์ได้ ranking ดีขึ้นใน search engines
- Title: 50-60 ตัวอักษร (มี keywords)
- Meta description: 150-160 ตัวอักษร
- Headings hierarchy (h1-h6 เป็นลำดับ)
- Semantic HTML & internal links
- Alt text สำหรับรูป
- Mobile-friendly & page speed
- Open Graph tags & Canonical URLs
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8" />
<!-- Title: 50-60 ตัวอักษร -->
<title>ชื่อเพจ - คำอธิบายสั้นๆ</title>
<!-- Meta description: 150-160 ตัวอักษร -->
<meta name="description" content="คำอธิบายหน้า" />
<meta name="keywords" content="keyword1, keyword2" />
<!-- Open Graph -->
<meta property="og:title" content="ชื่อเพจ" />
<meta property="og:image" content="image.jpg" />
<!-- Canonical URL -->
<link rel="canonical" href="https://example.com/page" />
</head>
</html>
6. Security Best Practices
ป้องกัน vulnerabilities และ attacks
- หลีกเลี่ยง inline event handlers (onclick, onerror)
- ใช้ Content Security Policy (CSP)
- Sanitize user input (ป้องกัน XSS)
- ใช้ HTTPS เสมอ
- Validate ทั้ง client-side และ server-side
- ระวัง CSRF attacks
- ใช้ SameSite cookie attribute
- ไม่เก็บ sensitive data ใน localStorage
<button onclick="alert('hello')">
Click
</button>
<button id="myBtn">Click</button>
<script>
document.getElementById("myBtn")
.addEventListener("click", () => {
alert("hello");
});
</script>
📚 สรุป
HTML5 มีคุณลักษณะมากมายที่ทำให้การพัฒนาเว็บสะดวกขึ้น และมี best practices ที่ช่วยให้สร้างเว็บไซต์ที่ดี:
- Semantic Tags - เพิ่มความหมายของเนื้อหา
- Form Validation - ตรวจสอบข้อมูลฝั่ง client
- Media Support - รองรับ video/audio ในตัว
- Canvas & SVG - วาดกราฟิกใน browser
- Web APIs - Geolocation, Storage, Fetch, Notification
- Responsive Design - ใช้ได้กับทุกอุปกรณ์