웹페이지에서 .js파일 비동기 방식으로 로드하기

  • Post author:
  • Post category:
  • Post comments:0 Comments
  • Post last modified:December 7, 2020

참고 :  http://www.phpied.com/async-javascript-callbacks/ , http://stackoverflow.com/questions/1834077/which-browsers-support-script-async-async , https://developers.google.com/analytics/devguides/collection/gajs/asyncTracking

본 문서는 Google Analytics Tracking Code 삽입과 관련한 예제를 바탕으로 작성 되었습니다.

웹페이지 호출 시 일반적으로 .js 파일은 다운로드 되고 파싱되는 절차를 거치게 되며 이 작업이 완료되기까지 대기 상태를 거쳐 페이지 로드가 완료되게 됩니다. 이 경우 .js 파일의 용량이 클 경우 페이지 로딩 시간이 길어지는 문제가 발생하게 되고 HTML5에서는 이를 보완하여 non-blocking한 동작을 지원하기 위해 Script 태그에 Async 속성이 추가 되었습니다.

HTML5의 경우 아직 Draft단계이기 때문에 추후 변동사항이 발생할 가능성이 있습니다. 의존 관계를 갖지 않는 단일 파일의 비동기 방식 로딩에 대한 예제는 다음과 같습니다.

(function() {
var foo = document.createElement('script'); foo.type = 'text/javascript'; foo.async = true;
foo.src = 'foo.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(foo, s);
})();

위 코드를 이용해서 의존 관계를 갖는 .js 파일의 로딩이나 코드의 수행을 위해 다음과 같이 수정해 보았습니다.

(function() {
var foo = document.createElement('script'); foo.type = 'text/javascript'; foo.async = true;
foo.src = 'foo.js';
foo.onload = foo.onreadystatechange = function() {
//subsequent executions..

foo.onload = foo.onreadystatechange = null;
}
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore foo, s);
})();

만약 jQuery를 사용할 수 있는 환경이라면 $.getScript(url, successCallback)을 사용 할 수 있습니다.

위 코드는 레거시 코드를 혼용해서 작성한 코드이기 때문에 IE7 모드 부터 동작하는 것을 확인 하였지만(본 블로그의 SyntaxHighlighter에 적용되어 있습니다 xD) 제가 알지 못하는 최신 브라우저에서만 지원하는 튜닝요소가 존재할 수 있습니다. 해당 기능을 정식으로 지원하는 브라우저는 다음과 같다고 합니다.

  • IE10+ (Preview2 이상)
  • Chrome 12+
  • Safari 5.1+
  • Firefox 4+
Author Details
Linus Lee aka y1sh former ATiMania.com sysop during 2001-2012. DevSecOps Engineer who likes tech, science, programming and solving problems 🙂
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments