Chrome 실전 가이드
Chrome의 핵심 개념과 실무 활용
학습 항목
이미지 로딩 중...
Chrome DevTools 기초부터 심화까지
Chrome DevTools의 필수 기능들을 실습 예제와 함께 배워봅니다. 디버깅, 네트워크 분석, 성능 최적화까지 개발자 도구를 완벽하게 활용하는 방법을 소개합니다.
들어가며
이 글에서는 Chrome DevTools 기초부터 심화까지에 대해 상세히 알아보겠습니다. 총 10가지 주요 개념을 다루며, 각각의 개념에 대한 설명과 실제 코드 예제를 함께 제공합니다.
목차
- Console_API_활용
- Debugger_문_사용
- DOM_Breakpoint_설정
- Network_요청_모니터링
- Performance_측정
- Memory_Leak_감지
- Sources_패널_디버깅
- Lighthouse_성능_분석
- CSS_검사_및_수정
- Application_Storage_관리
1. Console_API_활용
개요
console 객체의 다양한 메서드를 활용하여 효과적으로 디버깅할 수 있습니다.
코드 예제
console.log('기본 로그');
console.warn('경고 메시지');
console.error('에러 메시지');
console.table([{name: 'Alice', age: 25}, {name: 'Bob', age: 30}]);
console.group('그룹 시작');
console.log('그룹 내용');
console.groupEnd();
설명
console.table()로 배열을 표 형태로 보기 쉽게 출력하고, console.group()으로 로그를 구조화할 수 있습니다.
2. Debugger_문_사용
개요
debugger 키워드를 사용하면 코드 실행을 중단하고 디버깅을 시작할 수 있습니다.
코드 예제
function calculateTotal(items) {
let total = 0;
debugger; // 여기서 실행 중단
for (let item of items) {
total += item.price;
}
return total;
}
설명
debugger 문이 실행되면 DevTools가 자동으로 열리고 해당 지점에서 변수 값과 호출 스택을 확인할 수 있습니다.
3. DOM_Breakpoint_설정
개요
특정 DOM 요소의 변경사항을 추적하여 언제 수정되는지 파악할 수 있습니다.
코드 예제
// HTML: <div id="target">변경될 요소</div>
const target = document.getElementById('target');
// DevTools에서 우클릭 > Break on > subtree modifications
setTimeout(() => {
target.textContent = '변경됨!';
}, 2000);
설명
Elements 패널에서 요소를 우클릭하여 DOM Breakpoint를 설정하면 속성, 자식 노드, 제거 시점을 감지할 수 있습니다.
4. Network_요청_모니터링
개요
fetch 요청의 타이밍과 응답을 Network 탭에서 상세하게 분석할 수 있습니다.
코드 예제
async function fetchUserData() {
console.time('API 요청');
const response = await fetch('https://api.example.com/users');
const data = await response.json();
console.timeEnd('API 요청');
return data;
}
설명
console.time()으로 요청 시간을 측정하고, Network 탭에서 헤더, 페이로드, 응답 내용을 확인할 수 있습니다.
5. Performance_측정
개요
Performance API를 사용하여 코드의 실행 시간을 정확하게 측정할 수 있습니다.
코드 예제
performance.mark('start');
// 무거운 작업 시뮬레이션
for (let i = 0; i < 1000000; i++) {
Math.sqrt(i);
}
performance.mark('end');
performance.measure('작업 시간', 'start', 'end');
console.log(performance.getEntriesByType('measure'));
설명
Performance 탭에서 측정된 마크와 시간을 시각적으로 확인하고 병목 구간을 찾을 수 있습니다.
6. Memory_Leak_감지
개요
메모리 누수를 찾기 위해 객체 참조를 추적하고 힙 스냅샷을 비교할 수 있습니다.
코드 예제
let leakyArray = [];
function createLeak() {
setInterval(() => {
leakyArray.push(new Array(1000).fill('data'));
console.log('배열 크기:', leakyArray.length);
}, 1000);
}
// Memory 탭에서 힙 스냅샷 촬영하여 비교
설명
Memory 패널에서 힙 스냅샷을 여러 번 찍어 비교하면 계속 증가하는 객체를 발견하여 메모리 누수를 찾을 수 있습니다.
7. Sources_패널_디버깅
개요
Sources 패널에서 브레이크포인트를 설정하고 단계별로 코드를 실행할 수 있습니다.
코드 예제
function processData(data) {
const filtered = data.filter(x => x > 10);
const mapped = filtered.map(x => x * 2);
const result = mapped.reduce((a, b) => a + b, 0);
return result;
}
processData([5, 15, 20, 8, 30]);
설명
Sources 패널에서 라인 번호를 클릭하여 브레이크포인트를 설정하고 Step Over, Step Into로 코드를 한 줄씩 실행하며 변수를 확인합니다.
8. Lighthouse_성능_분석
개요
Lighthouse를 실행하여 웹 페이지의 성능, 접근성, SEO 점수를 자동으로 분석할 수 있습니다.
코드 예제
// HTML에 다음 최적화 적용
// <img src="image.jpg" alt="설명" loading="lazy">
// <link rel="preload" href="style.css" as="style">
document.addEventListener('DOMContentLoaded', () => {
console.log('페이지 로드 완료');
});
설명
Lighthouse 탭에서 분석을 실행하면 개선 제안 사항과 함께 성능, 접근성, SEO 점수를 확인할 수 있습니다.
9. CSS_검사_및_수정
개요
Elements 패널에서 실시간으로 CSS를 수정하고 결과를 즉시 확인할 수 있습니다.
코드 예제
// HTML: <div class="box">스타일 테스트</div>
const box = document.querySelector('.box');
box.style.backgroundColor = '#3498db';
box.style.padding = '20px';
box.style.borderRadius = '10px';
box.style.color = 'white';
설명
Elements 패널의 Styles 섹션에서 CSS 속성을 직접 수정하거나 추가하면 브라우저에 즉시 반영되어 테스트할 수 있습니다.
10. Application_Storage_관리
개요
Application 탭에서 LocalStorage, SessionStorage, Cookies를 확인하고 관리할 수 있습니다.
코드 예제
localStorage.setItem('user', JSON.stringify({name: 'John', id: 123}));
sessionStorage.setItem('token', 'abc123xyz');
document.cookie = 'theme=dark; max-age=3600';
console.log(localStorage.getItem('user'));
console.log(document.cookie);
설명
Application 탭에서 저장된 데이터를 확인하고 수정하거나 삭제할 수 있으며, 쿠키의 만료 시간과 속성도 확인할 수 있습니다.
마치며
이번 글에서는 Chrome DevTools 기초부터 심화까지에 대해 알아보았습니다. 총 10가지 개념을 다루었으며, 각각의 사용법과 예제를 살펴보았습니다.
관련 태그
#JavaScript #DevTools #Debugging #Performance #Network