Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีเขียน Script ใช้ W3C DOM หรือ IE4 DOM ตามความพร้อมใช้งาน


ใช้ Capability Testing (Feature Detection) ตรวจสอบว่า Browser รองรับ Method/Property ที่ต้องการหรือไม่ แล้วเลือก DOM ที่เหมาะสม

Code Snippet

if (document.getElementById) {
  // W3C DOM Method พร้อมใช้งาน
  var element = document.getElementById("myId");
} else if (document.all) {
  // IE4 DOM (document.all) พร้อมใช้งาน
  var element = document.all["myId"];
} else {
  // Fallback: Legacy DOM
  // เข้าถึงผ่าน document.forms, document.images, etc.
}

หลักการ Capability Testing

  1. ตรวจสอบ Feature ที่ต้องการโดยตรง (if (document.getElementById))
  2. ไม่ใช้ Browser Detection (User Agent Sniffing) - ไม่เชื่อถือได้
  3. เรียงลำดับจาก Standard/Modern ไป Legacy
  4. มี Fallback สำหรับ Browser เก่า

ตัวอย่างครบถ้วน: Cross-Browser getElementById

function getElement(id) {
  if (document.getElementById) {
    return document.getElementById(id); // W3C Standard (Modern Browsers, IE5.5+)
  } else if (document.all) {
    return document.all[id]; // IE4, IE5
  } else if (document.layers) {
    return document.layers[id]; // Netscape 4 (Legacy)
  }
  return null;
}

Feature Detection vs Browser Detection

วิธีตัวอย่างข้อดี/ข้อเสีย
Feature Detectionif (document.getElementById)✅ เชื่อถือได้, Future-proof, Standard
Browser Detectionif (navigator.userAgent.indexOf('MSIE') > -1)❌ แบก, ไม่เชื่อถือได้, Maintenance ยาก

Modern Approach (2020+)

Browser ทุกตัวรองรับ W3C DOM แล้ว (IE11+ รองรับเต็มที่) ไม่ต้อง Branch แล้ว:

// Modern Code - ไม่ต้อง Feature Detection
const element = document.getElementById("myId");
// หรือ
const element = document.querySelector("#myId");

Polyfill สำหรับ IE เก่า (ถ้าจำเป็น)

// getElementById Polyfill for IE4
if (!document.getElementById) {
  document.getElementById = function(id) {
    return document.all[id];
  };
}

สรุป

    ใช้ Feature Detection ไม่ใช่ Browser Detection
  • เรียง: W3C DOM → IE4 DOM → Legacy DOM
  • ปัจจุบัน: ใช้ W3C DOM เท่านั้นเพียงพอ (IE11+ ทุก Browser)
  • Polyfill ช่วยเติม Feature ที่ขาดใน Browser เก่า