[etc] javascript가 동작하는 순서

exoluse·2023년 7월 27일
0

etc

목록 보기
13/16

Html

<html>

<head>
<script src="https://code.jquery.com/jquery-3.7.0.js" integrity="sha256-JlqSTELeR4TLqP0OG9dxM7yDPqX1ox/HfgiSLBj8+kM=" crossorigin="anonymous"></script>
<script>

// 1. (즉시 실행)
console.log("즉시실행 - 1");

// 2. (즉시 실행)
(function() {
	console.log("(function() {");
})();


// 3. (즉시 실행)
test();


// 8. jquery ready 함수 (어쩄든 가장 나중에 실행)
$(function() {
	console.log("jquery $(function() -- 1");
});
$(document).ready(function(){ 
	console.log("$(document).ready");
});


// 6. 바깥의 스크립트가 모두 실행된 후 (jquery 보다는 빨리 실행)
window.addEventListener("DOMContentLoaded", function () {
	console.log("DOMContentLoaded -- 1");
});

// 7. DOMContentLoaded 가 수행된 후
window.onload = function() { 
	console.log("window load");
};

// 4. (즉시 실행)
console.log("즉시실행 - 2");


function test () {
	console.log("즉시실행 func");
}

</script>

</head>

<body>

<script>
// 5 (즉시 실행)
console.log("즉시 실행 in body");
</script>

</body>

</html>

결과

  1. top level 의 스크립트
  2. DOMContentLoaded
  3. window.load
  4. jquery document ready

순으로 실행된다.

1개의 댓글

comment-user-thumbnail
2023년 7월 27일

정리가 잘 된 글이네요. 도움이 됐습니다.

답글 달기