JavaScript에서 페이지가 로드될 때 비동기 코드를 실행하려면 async와 await를 <body> 태그의 onLoad 속성과 함께 사용하면 됩니다. 아래 예제를 통해 구체적인 방법을 살펴보겠습니다.
예제 코드
다음은 index.html 파일의 전체 코드입니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body onLoad="callFunction()">
<script>
async function callFunction(){
await testFunction();
}
function testFunction(){
console.log("Hi...");
}
</script>
</body>
</html>코드 설명
<body onLoad="callFunction()">: 페이지 로딩이 완료되면callFunction()이 자동으로 호출됩니다.async function callFunction(): 함수 앞에async키워드를 붙여 비동기 함수로 선언합니다.await testFunction():await를 사용해testFunction()의 실행이 완료될 때까지 기다린 후 다음 작업을 진행합니다.
실행 방법
위 프로그램을 실행하려면 파일 이름을 "index.html"과 같은 형태로 저장한 뒤, VS Code 편집기에서 해당 파일을 마우스 오른쪽 버튼으로 클릭하고 “Open with Live Server”(Live Server로 열기) 옵션을 선택하세요.
실행 결과
위 코드를 실행하면 브라우저 콘솔에 다음과 같은 출력 결과가 표시됩니다.
Hi...
이처럼 async/await를 활용하면 페이지 로드 시점에 비동기 작업을 깔끔하게 처리할 수 있으며, 콜백 지옥 없이 가독성 좋은 코드를 작성할 수 있습니다.