Skip to content

Instantly share code, notes, and snippets.

@yamoo9
Last active May 4, 2019 13:44
Show Gist options
  • Save yamoo9/cb98e6df7aea10d619879f6c5dbb73e5 to your computer and use it in GitHub Desktop.
Save yamoo9/cb98e6df7aea10d619879f6c5dbb73e5 to your computer and use it in GitHub Desktop.
JSONP 헬퍼 함수
function jsonp(url, callback, time_limit, log){
// 고유 아이디 생성
var unique_id = Math.floor(Math.random() * 100000);
// 콜백 함수 이름 설정
var jsonpCb = 'jsonpCb_' + unique_id;
// 임시 <script> 요소 생성
var s = document.createElement('script');
// 임시 <script> 요소에 src 속성 값으로 JSONP 설정
s.src = url + '?callback=' + jsonpCb;
// 임시 <script> 요소 문서에 추가
document.head.insertAdjacentElement('beforeend', s);
// JSONP 콜백 함수를 전역에 생성
window[jsonpCb] = callback;
// 사용 후, 불필요한 임시 <script> 요소 제거
s.remove ? s.remove() : s.parentNode.removeChild(s);
// 사용 후, 불필요한 window[jsonpCb] 제거
window.setTimeout(function(){
// log 옵션 값이 true 일 경우, 로드 출력
log && console.info('JSONP 콜백함수: ' + jsonpCb + '를 전역에서 제거했습니다.');
// window[jsonpCb] 제거
delete window[jsonpCb];
}, (time_limit || 3) * 1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment