ใน HTML documents คุณสามารถเขียน comments ที่ไม่ถูก interpret โดย web browser วัตถุประสงค์ของ comments ใน HTML files คือ เพื่อ document (อธิบาย) โค้ดสั้นๆ ไม่ว่าจะสำหรับตัวเองหรือสมาชิกในทีม
เพื่อเพิ่ม comment ใน HTML document เราใช้ opening และ closing comment tags: <!-- --> พร้อมข้อความภายใน เช่น:
<!-- Here is a comment on a single line -->
HTML comments สามารถเป็นหลายบรรทัดได้:
<!-- Here is a comment. Here is another comment. -->
Note: เมื่อฉันพูดว่า HTML comments ไม่ถูก interpret โดย web browser หมายถึง comments จะไม่ visible ให้ผู้เยี่ยมชมเว็บไซต์ ยกเว้นจะ right-click และกด View Page Source นี่คือเหตุผลที่คุณไม่ควรเขียน sensitive information ใน comments เช่น passwords
เขียน comments ใน HTML code ถือเป็น good practice ไหม?
ขึ้นอยู่กับถามใคร บาง developers ตัดสินไม่ใช้ comments ใน code files โดยทั่วไป แนะนำว่า code ควร explicit และ self-explanatory ผมไม่ซื้อidea นั้น เพราะ developers มีความคิดต่างกันเกี่ยวกับอะไรคือ explicit และ implicit
ผมมุ่งทำให้สิ่งต่างๆ ชัดเจนที่สุด ผมชอบอธิบายมากเกินไปกว่าน้อยเกินไป โดยเฉพาะ beginners ได้ประโยชน์จาก extra hand-holding ตอนเริ่มเรียน
Comments vs Page Load (Performance)
Downside หลักของ comments ใน HTML documents คือมันใช้พื้นที่บ้าง เพิ่ม size ของ build และส่งผลต่อ page loading แต่เป็นแค่ theoretical problem ไม่เคยได้ยินเว็บไซต์ไหนได้ performance boost มากจากการ strip out comments Comments ใช้พื้นที่ relative น้อยมาก จึง ridiculous ที่จะ stress เรื่องนี้
100 lines ของ HTML comments ใช้พื้นที่ประมาณ 1KB — แต่นั่นคือ without gzipping (compression method) ซึ่งจะทำน้อยลงอีกมาก
Comments ควรสั้นและตรงประเด็น ดังนั้นหากคุณไม่ได้คิดจะเขียนนิยายเล่มถัดไปใน HTML comments อย่ากังวล
แทนที่จะกังวล ให้ไปปรับปรุง image file compression บน site ใช้ better compression method บนแค่ single image หนึ่งรูป อาจ improve page load มากกว่า strip out 1000s lines ของ HTML comments เพื่อให้เห็น perspective