"자바스크립트에서 js import"의 두 판 사이의 차이

잔글 (봇: 자동으로 텍스트 교체 (-==참고 자료== +==참고==))
잔글 (봇: 자동으로 텍스트 교체 (-</source> +</syntaxhighlight>, -<source +<syntaxhighlight ))
 
10번째 줄: 10번째 줄:
==방법 1: JavaScript==
==방법 1: JavaScript==
;import.php
;import.php
<source lang='html'>
<syntaxhighlight lang='html'>
<script>
<script>
function loadScript(url, callback) {
function loadScript(url, callback) {
23번째 줄: 23번째 줄:
loadScript('import_hello.js', myloaded);
loadScript('import_hello.js', myloaded);
</script>
</script>
</source>
</syntaxhighlight>
;import_a.js
;import_a.js
<source lang='javascript'>
<syntaxhighlight lang='javascript'>
var str = 'hello';
var str = 'hello';
</source>
</syntaxhighlight>
*예제: http://zetawiki.com/ex/js/import.php
*예제: http://zetawiki.com/ex/js/import.php


==방법 2: jQuery==
==방법 2: jQuery==
;import2.php
;import2.php
<source lang='html'>
<syntaxhighlight lang='html'>
<script src="//code.jquery.com/jquery.min.js"></script>
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
<script>
39번째 줄: 39번째 줄:
});
});
</script>
</script>
</source>
</syntaxhighlight>
*예제: http://zetawiki.com/ex/js/import2.php
*예제: http://zetawiki.com/ex/js/import2.php


==방법 3: jQuery 2==
==방법 3: jQuery 2==
<source lang='html'>
<syntaxhighlight lang='html'>
<script src="//code.jquery.com/jquery.min.js"></script>
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
<script>
49번째 줄: 49번째 줄:
document.write(str); // hello 출력됨
document.write(str); // hello 출력됨
</script>
</script>
</source>
</syntaxhighlight>
*예제: http://zetawiki.com/ex/js/import3.php
*예제: http://zetawiki.com/ex/js/import3.php



2020년 11월 2일 (월) 02:52 기준 최신판

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 }}