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

เรียกโค้ด Asynchronous จาก index.html ใน JavaScript

ใช้ async/await ร่วมกับ event onload ของ body

ตัวอย่างโค้ด (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body onLoad="callFunction()">
    <script>
        async function callFunction() {
            await testFunction();
        }

        function testFunction() {
            console.log("Hi...");
        }
    </script>
</body>
</html>

วิธีรันโปรแกรม

  1. บันทึกไฟล์ชื่อ "anyName.html" หรือ "index.html"
  2. คลิกขวาที่ไฟล์ เลือก "Open with Live Server" ใน VS Code Editor

ผลลัพธ์

แสดง "Hi..." ใน Console เมื่อหน้าเว็บโหลดเสร็จ