HTML <script>แท็ก
ตัวอย่าง
เขียนว่า "สวัสดีจาวาสคริปต์!" ด้วยจาวาสคริปต์:
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
ความหมายและการใช้งาน
แท็ ก<script>
นี้ใช้เพื่อฝังสคริปต์ฝั่งไคลเอ็นต์ (JavaScript)
อิ ลิ<script>
เมนต์ประกอบด้วยคำสั่งสคริปต์ หรือชี้ไปที่ไฟล์สคริปต์ภายนอกผ่านแอททริบิวต์ src
การใช้งานทั่วไปสำหรับ JavaScript คือการจัดการรูปภาพ การตรวจสอบแบบฟอร์ม และการเปลี่ยนแปลงเนื้อหาแบบไดนามิก
เคล็ดลับและหมายเหตุ
เคล็ดลับ: โปรด ดูที่ องค์ประกอบ <noscript>สำหรับผู้ใช้ที่ปิดใช้งานสคริปต์ในเบราว์เซอร์ หรือมีเบราว์เซอร์ที่ไม่สนับสนุนสคริปต์ฝั่งไคลเอ็นต์
เคล็ดลับ:หากคุณต้องการเรียนรู้เพิ่มเติมเกี่ยวกับ JavaScript โปรดไปที่ บทช่วย สอน JavaScriptของ เรา
รองรับเบราว์เซอร์
Element | |||||
---|---|---|---|---|---|
<script> | Yes | Yes | Yes | Yes | Yes |
คุณลักษณะ
Attribute | Value | Description |
---|---|---|
async | async | Specifies that the script is downloaded in parallel to parsing the page, and executed as soon as it is available (before parsing completes) (only for external scripts) |
crossorigin | anonymous use-credentials |
Sets the mode of the request to an HTTP CORS Request |
defer | defer | Specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing (only for external scripts) |
integrity | filehash | Allows a browser to check the fetched script to ensure that the code is never loaded if the source has been manipulated |
nomodule | True False |
Specifies that the script should not be executed in browsers supporting ES2015 modules |
referrerpolicy | no-referrer no-referrer-when-downgrade origin origin-when-cross-origin same-origin strict-origin strict-origin-when-cross-origin unsafe-url |
Specifies which referrer information to send when fetching a script |
src | URL | Specifies the URL of an external script file |
type | scripttype | Specifies the media type of the script |
ความแตกต่างระหว่าง HTML และ XHTML
ใน XHTML เนื้อหาภายในสคริปต์จะถูกประกาศเป็น #PCDATA (แทน CDATA) ซึ่งหมายความว่าเอนทิตีจะถูกแยกวิเคราะห์
ซึ่งหมายความว่าใน XHTML อักขระพิเศษทั้งหมดควรได้รับการเข้ารหัส หรือเนื้อหาทั้งหมดควรอยู่ในส่วน CDATA:
<script type="text/javascript">
//<![CDATA[
var i = 10;
if (i < 5) {
// some code
}
//]]>
</script>
คุณสมบัติสากล
แท็ ก<script>
ยังสนับสนุน Global Attributes ในHTML
หน้าที่เกี่ยวข้อง
กวดวิชา HTML: สคริปต์ HTML
การอ้างอิง HTML DOM: Script Object
บทช่วยสอน JavaScript: เรียนรู้ JavaScript
การตั้งค่า CSS เริ่มต้น
เบราว์เซอร์ส่วนใหญ่จะแสดง<script>
องค์ประกอบด้วยค่าเริ่มต้นดังต่อไปนี้:
script {
display: none;
}