
JavaScript에서 유휴 시간 감지: 콘텐츠 프리페칭 및 프리로드 가이드
웹 개발에서 유휴 시간 감지는 사용자 경험을 최적화하는 데 매우 중요할 수 있습니다. 사용자 활동이 없거나 CPU 사용량이 최소화된 기간으로 정의되는 유휴 시간은 콘텐츠를 미리 가져오거나 미리 로드하여 페이지 로드 시간을 줄이고 응답성을 향상시킬 수 있는 기회를 제공합니다.
바닐라 JavaScript에서 유휴 시간 감지 구현
바닐라 JavaScript에서 유휴 시간 감지를 활성화하려면 다음 접근 방식을 활용하세요.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | var inactivityTime = function () {
var time;
window.onload = resetTimer;
document.onmousemove = resetTimer;
document.onkeydown = resetTimer;
function logout() {
alert( "You are now logged out." )
}
function resetTimer() {
clearTimeout(time);
time = setTimeout(logout, 3000)
}
};
|
로그인 후 복사
초기화 및 사용자 정의
inactivityTime 함수가 정의되면 원하는 위치(예: onPageLoad)에서 초기화하세요.
1 2 3 | window.onload = function () {
inactivityTime();
}
|
로그인 후 복사
다음을 포함하여 더 많은 DOM 이벤트를 추가하여 이벤트 리스너를 추가로 사용자 정의할 수 있습니다.
1 2 3 4 5 6 7 | document.onload = resetTimer;
document.onmousemove = resetTimer;
document.onmousedown = resetTimer;
document.ontouchstart = resetTimer;
document.onclick = resetTimer;
document.onkeydown = resetTimer;
document.addEventListener( 'scroll' , resetTimer, true);
|
로그인 후 복사
또는 array:
1 2 3 4 5 | window.addEventListener( 'load' , resetTimer, true);
var events = [ 'mousedown' , 'mousemove' , 'keypress' , 'scroll' , 'touchstart' ];
events.forEach( function (name) {
document.addEventListener(name, resetTimer, true);
});
|
로그인 후 복사
스크롤 가능한 요소 내에서 스크롤이 발생하면 window.onscroll이 실행되지 않습니다. 이 문제를 해결하려면 window.addEventListener('scroll', ResetTimer, true)에 세 번째 인수를 포함시켜 캡처 단계에서 이벤트를 캡처하세요.
위 내용은 콘텐츠 미리 가져오기 및 미리 로드를 최적화하기 위해 JavaScript에서 유휴 시간을 어떻게 감지할 수 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!