상세 컨텐츠

본문 제목

[JavaScript] js파일에 다른 js파일 include 하기 관련 How to include js file in another js file? [duplicate] Ask

WEB/JavaScript

by AlrepondTech 2018. 4. 11. 12:21

본문

반응형
728x170

 

 

 

 

 

=================================

=================================

=================================

 

 

 

 

 

 

 

출처: https://stackoverflow.com/questions/4634644/how-to-include-js-file-in-another-js-file?lq=1

 

 

Possible Duplicate:
Including a .js file within a .js file

How can I include a js file into another js file , so as to stick to the DRY principle and avoid duplication of code.

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

You can only include a script file in an HTML page, not in another script file. That said, you can write JavaScript which loads your "included" script into the same page:

var imported = document.createElement('script'); imported.src = '/path/to/imported/script'; document.head.appendChild(imported);

There's a good chance your code depends on your "included" script, however, in which case it may fail because the browser will load the "imported" script asynchronously. Your best bet will be to simply use a third-party library like jQuery or YUI, which solves this problem for you.

// jQuery $.getScript('/path/to/imported/script.js', function() {     // script is now loaded and executed.     // put your dependent JS here. });

I can only repeat: in case of usage $.getScript the second depended script will be started to load after the first one is loaded and executed. It is sequential instead of parallel loading. Moreover if somebody include per <script> such loader.js file, which load some JavaScript library (think about jQuery UI for example), than one can not just load the main.js which use the library in the next <script>. So the usage of JavaScript library will be not so easy as usual. For understanding: I would like to use the way, but one should suggest some more to make it practicable

------

In case of your first suggestion one have to use imported.onload to cascade the scripts. But in the case we continue to have the same problems which I described. 

-----

If you will use "Timelines" of Developer Tools of Google Chrome for example, you can verify that ok-soft-gmbh.com/jqGrid/iedeveloper.htm used document.writeln loads scripts parallel and execute (evaluate) in the same correct order. The page is XHTML and so the first the statements fromstackoverflow.com/questions/802854/… are also wrong. So didn't found and reason (which I could verified) why it is bad to use document.writeln inside of <script> placed in the <head>. I would like it somebody post me one.

 

------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

I disagree with the critic of document.write technique (see suggestion of Vahan Margaryan). I like the way document.getElementsByTagName('head')[0].appendChild(...) (see suggestion of Matt Ball), but there are one important problem: the order of executing of the scripts included in the way. I have to describe the problem more exactly below.

Recently I spend many time to reproduce one close problem. Well-knows jQuery plugin use the same technique (see src here) to load the files, but different people had reported problem with working of this. I can describe the problem as following. Let us you have JavaScript library which consist from many scripts and one loader.js loads all the parts. Some from the parts are depend from another. Let us you include another main.js script per <script> which use the objects from loader.js immediately after the loader.js. The problem was that sometime, the main.js are executed before all scripts loaded by loader.js. The usage of $(document).ready(function () {/*code here*/}); inside of main.js script could also not help. The usage of cascading onloadevent handler in the loader.js will follow to sequential instead of parallel loading of the scripts and will make difficult to use main.js script which should be just includes somewhere after loader.js.

I could reproduce the problem in my environment and can see that the order of executing of the scripts in Internet Explorer 8 can be another as the order of including of JavaScripts. It is very hard problem if you need include some scripts where one depends from another. The problem and is described in Loading Javascript files in parallel. As the workaround are suggested to use document.writeln:

document.writeln("<script type='text/javascript' src='Script1.js'></script>"); document.writeln("<script type='text/javascript' src='Script2.js'></script>");

It is described that in the case "the scripts are downloaded in parallel but executed in the order they're written to the page". After changing from document.getElementsByTagName('head')[0].appendChild(...) technique to document.writeln I had never seen any problem more.

So I recommend you to use document.writeln.

UPDATED: If somebody have an interest he can try to load (and reload) the page in Internet Explorer (the page use document.getElementsByTagName('head')[0].appendChild(...) technique) and compare with the fixed version used document.writeln. (The code of the page is relatively dirty and is not from me, but it can be used to reproduce the problem which I describe).

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

It is not possible directly. You may as well write some preprocessor which can handle that.

If I understand it correctly then below are the things that can be helpful to achieve that:

  • Use a pre-processor which will run through your JS files for example looking for patterns like "@import somefile.js" and replace them with the content of the actual file. Nicholas Zakas(Yahoo) wrote one such library in Java which you can use (http://www.nczonline.net/blog/2009/09/22/introducing-combiner-a-javascriptcss-concatenation-tool/)
  • If you are using Ruby on Rails then you can give Jammit asset packaging a try, it uses assets.yml configuration file where you can define your packages which can contain multiple files and then refer them in your actual webpage by the package name.
  • Try using a module loader like RequireJS or a script loader like LabJs with the ability to control the loading sequence as well as taking advantage of parallel downloading.

JavaScript currently does not provide a "native" way of including a JavaScript file into another like CSS ( @import ), but all the above mentioned tools/ways can be helpful to achieve the DRY principle you mentioned. I can understand that it may not feel intuitive if you are from a Server-side background but this is the way things are. For front-end developers this problem is typically a "deployment and packaging issue".

Hope it helps.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

You need to write so

document.write('<scr'+'ipt type="text/javascript" src="other js file.js" ></scr'+'ipt>');

in your first js file

 

 

 

 

반응형

 

728x90

 

 

 

=================================

=================================

=================================

 

 

 

출처: https://stackoverflow.com/questions/26979733/how-to-include-an-external-javascript-file-conditionally

 

 

This question has been asked before in Include a Javascript File in another Javascript File. This peice of code may fit what you have been looking for

function include(filename) {    var head = document.getElementsByTagName('head')[0];     var script = document.createElement('script');    script.src = filename;    script.type = 'text/javascript';     head.appendChild(script) }   

if that script does not work, i suggest you to look over and read the post above: Include a Javascript File in another Javascript File.

I hope this helps, it may not be the answer you had been looking for, but it may just help.

 

 

=================================

=================================

=================================

 

 

 

출처:  https://zetawiki.com/wiki/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8%EC%97%90%EC%84%9C_js_import

 

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 참고[편집]

 

 

 

=================================

=================================

=================================

 

 

반응형
그리드형


관련글 더보기

댓글 영역