자바스크립트에서 js import

1 개요[ | ]

How to include a javascript file in another javascript file
JavaScript에서 js import
자바스크립트에서 자바스크립트 import
  • 방법 1, 2는 callback 함수 내부에서만 제대로 이용할 수 있다.
별도의 문서로 불러오는 방식
  • 방법 3은 callback 함수 필요없이, HTML에서 import하는 것과 동일하게 이용할 수 있다.
문서 자신의 헤드에 붙이는 방식

2 방법 1: JavaScript[ | ]

import.php
<script>
function loadScript(url, callback) {
	var script = document.createElement('script');
	script.src = url;
	script.onload = callback;
	document.getElementsByTagName('head')[0].appendChild(script);
}
var myloaded = function() {
	document.write(str); // hello 출력됨
}
loadScript('import_hello.js', myloaded);
</script>
import_a.js
var str = 'hello';

3 방법 2: jQuery[ | ]

import2.php
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$.getScript("import_hello.js", function() {
	document.write(str); // hello 출력됨
});
</script>

4 방법 3: jQuery 2[ | ]

<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$('head').append('<script src=\'import_hello.js\'><\/script>');
document.write(str); // hello 출력됨
</script>

5 같이 보기[ | ]

6 참고[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}