code

.js 파일에 .js 파일 포함

codestyles 2020. 9. 17. 07:55
반응형

.js 파일에 .js 파일 포함 [중복]


이 질문에 이미 답변이 있습니다.

.js다른 .js파일에 파일 을 포함 할 수 있는지 알고 싶습니다 .

내가 이것을하고 싶은 이유는 클라이언트 포함을 최소한으로 유지하기 위해서입니다. .js클라이언트에 필요한 기능으로 이미 작성된 여러 파일이 있습니다. 클라이언트는 .js파일 포함 (내 .js파일)으로 관리하는 html 파일을 갖게 됩니다.

.js모든 기능이 포함 된 파일을 다시 작성 하거나 이중 작업을 피하기 위해 .js다른 .js파일 을 포함 하는 파일 을 작성하는 방법을 알아낼 수 있습니다.


나는 기본적으로 이것을 좋아하고, 새로운 요소를 생성하고 <head>

var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);

onload첨부 한 각 스크립트에 이벤트를 사용할 수도 있지만 테스트 해 보시기 바랍니다. 브라우저 간 작동 여부가 확실하지 않습니다.

x.onload=callback_function;

브라우저로드 시간에 가장 적합한 솔루션은 서버 측 스크립트를 사용하여 모두 하나의 큰 .js 파일로 결합하는 것입니다. 최종 버전을 gzip / 최소화하십시오. 단일 요청-멋지고 컴팩트합니다.

또는 DOM을 사용하여 <script>태그 를 만들고 여기에 src 속성을 설정 한 다음 <head>. 해당 기능이로드 될 때까지 기다려야하는 load경우 해당 스크립트 태그 이벤트에서 나머지 자바 스크립트 파일이 호출되도록 할 수 있습니다 .

이 함수는 jQuery의 기능을 기반으로합니다. $.getScript()

function loadScript(src, f) {
  var head = document.getElementsByTagName("head")[0];
  var script = document.createElement("script");
  script.src = src;
  var done = false;
  script.onload = script.onreadystatechange = function() { 
    // attach to both events for cross browser finish detection:
    if ( !done && (!this.readyState ||
      this.readyState == "loaded" || this.readyState == "complete") ) {
      done = true;
      if (typeof f == 'function') f();
      // cleans up a little memory:
      script.onload = script.onreadystatechange = null;
      head.removeChild(script);
    }
  };
  head.appendChild(script);
}

// example:
loadScript('/some-other-script.js', function() { 
   alert('finished loading');
   finishSetup();
 });

이를 수행하는 직접적인 방법은 없습니다.

What you can do is load the script on demand. (again uses something similar to what Ignacio mentioned,but much cleaner).

Check this link out for multiple ways of doing this: http://ajaxpatterns.org/On-Demand_Javascript

My favorite is(not applicable always):

<script src="dojo.js" type="text/javascript">
dojo.require("dojo.aDojoPackage");

Google's closure also provides similar functionality.


A popular method to tackle the problem of reducing JavaScript references from HTML files is by using a concatenation tool like Sprockets, which preprocesses and concatenates JavaScript source files together.

Apart from reducing the number of references from the HTML files, this will also reduce the number of hits to the server.

You may then want to run the resulting concatenation through a minification tool like jsmin to have it minified.


I use @gnarf's method, though I fall back on document.writelning a <script> tag for IE<7 as I couldn't get DOM creation to work reliably in IE6 (and TBH didn't care enough to put much effort into it). The core of my code is:

if (horus.script.broken) {
    document.writeln('<script type="text/javascript" src="'+script+'"></script>');   
    horus.script.loaded(script);
} else {
    var s=document.createElement('script');
    s.type='text/javascript';
    s.src=script;
    s.async=true;

    if (horus.brokenDOM){
        s.onreadystatechange=
            function () {
                if (this.readyState=='loaded' || this.readyState=='complete'){
                    horus.script.loaded(script);
                }
        }
    }else{
        s.onload=function () { horus.script.loaded(script) };
    }

    document.head.appendChild(s);
}

where horus.script.loaded() notes that the javascript file is loaded, and calls any pending uncalled routines (saved by autoloader code).

참고URL : https://stackoverflow.com/questions/2145914/including-a-js-file-within-a-js-file

반응형