본문 바로가기
프로그래밍 놀이터/Web

[jQuery/Tutorial] window.onload vs. ($document).ready

by 돼지왕 왕돼지 2013. 5. 8.
반응형

출처 : jQuery 공식 홈페이지.


window.onload 는 html 의 모든 load 가 완료되었을 때 불린다.

따라서 이미지가 있을 경우, 로드가 완료될 떄까지 onload 에 있는 코드는 실행되지 않는다.


반면에 jQuery의 $(document).ready 는 사용자의 조작이 가능해진 순간에 불린다.

따라서 onload 보다 조금 더 실용적이다.


<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>Demo</title>

</head>

<body>

<a href="http://jquery.com/">jQuery</a>

<script src="jquery.js"></script>

<script>

/*

window.onload = function(){

alert( "Welcome" );

}

*/

$( document ).ready( function(){

$( "a" ).click( function( event ){

alert( "Thanks for visiting!" );

event.preventDefault();

});

});

</script>

</body>

</html>




event.preventDefault() 는 원래 기본 동작을 방지한다.

위의 예에는 event.preventDefault() 코드가 들어가서 a 의 기본동작인 link 로의 연결이 되지 않는다.



반응형

댓글