티스토리 뷰
console.log('out__top')
function foo() {
console.log('foo');
}
$(window).on('load', function(){
console.log('jQuery - load')
})
$(document).ready(function () {
console.log('jQuery - ready');
})
$(function () {
console.log('jQuery - ready 축약')
})
window.addEventListener('DOMContentLoaded', function () {
console.log('DOMContentLoaded')
})
window.addEventListener('load', function () {
console.log('load')
})
window.onload = function () {
console.log('onload');
}
foo();
console.log('out__bottom')
[결과]
- 런타임 순서대로 out__top -> foo() -> out__bottom 실행을 한 뒤, 이벤트 들이 실행된다.
- 이벤트 중 DOMContentLoaded가 가장 빠르다. (HTML이 로드되면 실행)
$(document).ready(function () {
console.log('jQuery - ready');
})
$(function () { // ready를 축약한 것
console.log('jQuery - ready 축약')
})
// 위 코드를 JavaScript로 변경하면 아래와 같다.
window.addEventListener('DOMContentLoaded', function () {
console.log('DOMContentLoaded')
})
- jQuery의 ready와 ready 축약은 동일한 이벤트이기 때문에 런타임 순서에 따라 실행 순서가 달라진다.
(쉽게 말해, 축약을 ready 위에 쓰면 축약이 먼저 나오고, 축약을 ready 아래에 쓰면 축약이 나중에 나온다.)
$(window).on('load', function(){
console.log('jQuery - load')
})
// 위 코드를 JavaScript로 변경하면 아래와 같다.
window.addEventListener('load', function () {
console.log('load')
})
window.onload = function () {
console.log('onload');
}
- 위 코드는 작성 방법은 모두 다르지만 모두 동일한 이벤트이다.
- 위에서 설명한 ready와 같이 모두 동일한 이벤트이기 때문에 런타임 순서에 따라 실행 순서가 달라진다.
[공부 좌표]
[참고하면 좋은]
댓글