올바른 이해와 사용 방법
자바스크립트에서 현재 창을 새로고침하려면 window.location.reload() 메서드를 사용합니다.
이렇게 하면 '새로고침' 버튼처럼 현재 페이지의 리소스를 다시 불러와 새로고침합니다.
구문
window 객체는 생략할 수 있으며, 보통 location.reload()를 사용합니다.
location.reload();
// 또는 window.location.reload();
참고하세요!
window.location.reload() 메서드는 줄여서 location.reload()라고만 작성하는 경우도 많습니다.
브라우저에서는 window 객체가 전역 객체이므로, window.location는 줄여서 location만으로도 동일하게 사용할 수 있습니다.
특징
- 새로고침 버튼처럼 현재 리소스(HTML, CSS, 자바스크립트, 이미지 등)를 다시 불러옵니다.
- 현재 보고 있는 페이지의 주소(URL)는 변하지 않습니다.
- 새로운 페이지로 이동하는 것이 아니기 때문에 브라우저의 방문 기록(Session History)에 새로운 기록으로 추가되지 않습니다.
기본 예제
onclick 속성으로 버튼을 클릭했을 때, 현재 페이지 새로고침하기
<button type="button" onclick="location.reload()">새로고침하기</button>
<!-- 또는 -->
<button type="button" onclick="window.location.reload()">새로고침하기</button>
addEventListener() 메서드로 버튼을 클릭했을 때, 현재 페이지 새로고침하기
<button type="button" id="reload-btn">새로고침하기</button>
<script>
const reloadBtn = document.getElementById("reload-btn");
reloadBtn.addEventListener("click", () => {
location.reload();
// 또는 window.location.reload();
});
</script>
활용 예제
다음은 location.reload()를 활용하여 현재 페이지를 새로고침하는 간단한 활용 예제입니다.
이 페이지에는 타이머가 있습니다. 타이머는 바로 작동하고, '리셋 (새로고침)' 버튼을 클릭하면 페이지를 자동으로 새로고침하는 방식입니다.
예제 코드 블록 하단에 있는 '실제 적용된 모습' 버튼을 클릭하면 동작을 직접 확인할 수 있습니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>타이머 + 새로고침 예제</title>
<style>
body {
font-family: system-ui, -apple-system, sans-serif;
padding: 40px;
}
.timer {
font-size: 70px;
font-weight: bold;
color: red;
margin-bottom: 20px;
}
button {
padding: 10px 16px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>타이머 + location.reload() 예제</h1>
<div class="timer" id="timer">0</div>
<button type="button" id="resetBtn">리셋 (새로고침)</button>
<script>
let time = 0;
let intervalId = null;
const timerEl = document.getElementById("timer");
const resetBtn = document.getElementById("resetBtn");
function render() {
timerEl.textContent = time;
}
function tick() {
time++;
render();
}
intervalId = setInterval(tick, 1000);
resetBtn.addEventListener("click", () => {
location.reload();
});
render();
</script>
</body>
</html>
실제 적용된 모습
명세서
| 명세서 사양 | |
|---|---|
window.location.reload()
|
HTML #dom-location-reload-dev |
브라우저 호환성
| 메서드 |
데스크탑 Chrome
|
데스크탑 Edge
|
데스크탑 Firefox
|
Safari
|
|---|---|---|---|---|
window.location.reload()
|
1 | 12 | 1 | 1 |