아주 어처구니 없는 상황이 있어서 메모해 둔다...
테스트 환경은 frame > document 에서 실행
(frame과 상관없는 것 같음. 똑같은 환경 다른 사이트는 잘 작동함)
$(function) / $(document).ready
DOM이 생성되었을 시점에 실행할 스크립트를 jQuery를 사용할 때 다음과 같이 사용한다.
$(function() {
console.log("test");
});
위 이미지 처럼 글쓴이는 <head></head>
안에 jQuery 스크립트가 선언되어있다. 하지만 개발자도구에 찍힌 로그는 빈란..
그래서 먼저 체크한 것은 정말로 jQuery가 로드가 되었는지 확인할 필요가 있어서 다음처럼 스크립트를 추가했다.
// jQuery 존재하는지 판단하여 없으면 스크립트 CDN 삽입
if (typeof jQuery == 'undefined') {
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "https://code.jquery.com/jquery-3.5.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
} else {
console.log("jQuery Ready");
}
실행해보니 다음처럼 로드는 되었다는 것을 알 수 있었다.
그렇다면 왜 $(function)
이 먹히지 않는가 ? 생각되어 좀 더 풀어서 시도해보았다.
$(document).ready(function() {
console.log("test");
});
현재 document
에 ready()
function이 없다고 나온다. 어처구니 없네
그래서 완전 초기버전으로 시도했더니 결과는 다음과 같았다.
jQuery(document).ready(function() {
console.log("test");
});
원인발생 및 해결방안
혹시 라이브러리를 사용하는 것 중에 다음 스크립트가 있다면 이 녀석이 범인일 수 있다.
http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js
prototype
은 $
를 사용하기 때문에 jQuery와 같이 사용하면 에러가 발생할 수 있다.
따라서 기본적으로 다음과 같은 스크립트는 에러를 발생시킨다.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js" type="text/javascript"></script>
// "$" prototype이 참조하여 여기서 에러발생
$(function() {
console.log("test");
});
// 혹은
$(document).ready(function() {
console.log("test");
});
해결방안은 다음 스크립트 처럼 사용하면 된다.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js" type="text/javascript"></script>
// "$" prototype이 참조
<script>
( function($) {
// 여기서 "$"를 jQuery로 참조
$(function() {
console.log("test");
});
} ) ( jQuery );
</script>
아니면 prototype
를 사용하지말자 ! (옛 방식 !!!) $.ajax
를 사용하도록 하자prototype
을 사용하는 이유가 Ajax.Request
를 이용하여 Ajax
처리를 하려고하는 것 같은데 ... jQuery로 쓰자..
이미 소스가 지져분해져서 바꾸기 어렵다면 위 처럼 해결방안으로 소스를 작성하면된다. 앞 뒤로 2줄 추가하면 끝
'Frontend > jQuery' 카테고리의 다른 글
Unite Gallery 를 이용한 반응형 갤러리 만들기 (0) | 2020.12.03 |
---|---|
Back Forward Cache 익스, 크롬, 사파리, 파이어폭스 뒤로가기 이벤트 (2) | 2020.01.20 |
SCRIPT7002 ERROR & IE Browser (0) | 2020.01.07 |
sweetalert2 possible unhandled promise rejection (0) | 2019.12.16 |
로딩 심기 (0) | 2019.12.14 |