programing

jQuery $.getScript() 메서드를 사용하여 여러 js 파일을 포함하는 방법

lovejava 2023. 8. 7. 22:14

jQuery $.getScript() 메서드를 사용하여 여러 js 파일을 포함하는 방법

저는 js 파일에 javascript 파일을 동적으로 포함시키려고 합니다.저는 그것에 대해 조사를 해보았고 jQuery $.getScript() 방법이 바람직한 방법이라는 것을 발견했습니다.

// jQuery
$.getScript('/path/to/imported/script.js', function()
{
    // script is now loaded and executed.
    // put your dependent JS here.
    // what if the JS code is dependent on multiple JS files? 
});

그런데 이 방법이 한 번에 여러 스크립트를 로드할 수 있는지 궁금합니다.제가 이것을 묻는 이유는 때때로 제 자바스크립트 파일이 둘 이상의 js 파일에 의존하기 때문입니다.

잘 부탁드립니다.

그 대답은.

은 약을사용수있다니습할과 함께 사용할 수 .getScript()모든 스크립트가 로드될 때까지 기다립니다.

$.when(
    $.getScript( "/mypath/myscript1.js" ),
    $.getScript( "/mypath/myscript2.js" ),
    $.getScript( "/mypath/myscript3.js" ),
    $.Deferred(function( deferred ){
        $( deferred.resolve );
    })
).done(function(){
    
    //place your code here, the scripts are all loaded
    
});

피들

다른 바이올린

하여 의위코서지추연것고가하해내는결하서 안에서 것.$()j,▁▁insidequ다▁is같니▁placingqu와 같이 jQuery 하는 것과 .$(func).

$(function() { func(); });

에서는 DOM이 준비될 때까지 기다립니다.$.when모든 스크립트가 로드되고 DOM이 준비될 때까지 기다립니다.$.DeferredDOM 준비 콜백에서 해결되는 콜입니다.


보다 일반적인 사용을 위해, 편리한 기능

임의의 스크립트 배열을 허용하는 유틸리티 함수는 다음과 같이 생성될 수 있습니다.

$.getMultiScripts = function(arr, path) {
    var _arr = $.map(arr, function(scr) {
        return $.getScript( (path||"") + scr );
    });
        
    _arr.push($.Deferred(function( deferred ){
        $( deferred.resolve );
    }));
        
    return $.when.apply($, _arr);
}

이렇게 사용할 수 있는.

var script_arr = [
    'myscript1.js', 
    'myscript2.js', 
    'myscript3.js'
];

$.getMultiScripts(script_arr, '/mypath/').done(function() {
    // all scripts loaded
});

여기서 경로는 모든 스크립트 앞에 추가되며 또한 선택 사항입니다. 즉, 배열에 전체 URL이 포함되어 있으면 이를 수행할 수 있으며 경로를 모두 제외할 수도 있습니다.

$.getMultiScripts(script_arr).done(function() { ...

인수, 오류 등

참로고, 주할점은의는 것에 하세요.done와 일치하는 되며, 각 에는 응답 " " " " " " " " " " " " " " " 을 .

$.getMultiScripts(script_arr).done(function(response1, response2, response3) { ...

서 각 에는 각배에다같것은것포입다니함이와 같은 됩니다.[content_of_file_loaded, status, xhr_object]으로 스크립트는으로 로드되기 "" "" "" "" "" "" "" "" "" " "" " " " " " " " " " " " " " 입니다.done콜백은 모든 스크립트가 로드되었다는 것을 알고자 하는 모든 것입니다. 완전성을 위해, 그리고 로드된 파일의 실제 텍스트에 액세스해야 하거나 각 XHR 개체에 액세스해야 하는 드문 경우를 위해 추가하는 것입니다.

또한 스크립트 중 하나라도 로드하지 못하면 실패 처리기가 호출되고 이후 스크립트가 로드되지 않습니다.

$.getMultiScripts(script_arr).done(function() {
     // all done
}).fail(function(error) {
     // one or more scripts failed to load
}).always(function() {
     // always called, both on success and error
});

여러 스크립트를 병렬로 로드하는 간단한 기능을 구현했습니다.

기능.

function getScripts(scripts, callback) {
    var progress = 0;
    scripts.forEach(function(script) { 
        $.getScript(script, function () {
            if (++progress == scripts.length) callback();
        }); 
    });
}

사용.

getScripts(["script1.js", "script2.js"], function () {
    // do something...
});

다음과 같이 이전 스크립트의 콜백에 필요한 다음 스크립트를 로드합니다.

$.getScript('scripta.js', function()
{
   $.getScript('scriptb.js', function()
   {
       // run script that depends on scripta.js and scriptb.js
   });
});

스크립트를 특정 순서로 로드해야 하는 경우가 있습니다.예를 들어 jQuery UI보다 먼저 jQuery를 로드해야 합니다.이 페이지의 대부분의 예제는 스크립트를 병렬(비동기적)로 로드하므로 실행 순서가 보장되지 않습니다.지정하지 를 작성합니다.y은 에달있는에 .x둘 다 성공적으로 로드되었지만 순서가 잘못된 경우 손상될 수 있습니다.

종속 스크립트 + 옵션 병렬 로드 + 지연된 객체를 순차적으로 로드할 수 있는 하이브리드 접근 방식을 제안합니다.

/*
 * loads scripts one-by-one using recursion
 * returns jQuery.Deferred
 */
function loadScripts(scripts) {
  var deferred = jQuery.Deferred();

  function loadScript(i) {
    if (i < scripts.length) {
      jQuery.ajax({
        url: scripts[i],
        dataType: "script",
        cache: true,
        success: function() {
          loadScript(i + 1);
        }
      });
    } else {
      deferred.resolve();
    }
  }
  loadScript(0);

  return deferred;
}

/*
 * example using serial and parallel download together
 */

// queue #1 - jquery ui and jquery ui i18n files
var d1 = loadScripts([
  "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js",
  "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"
]).done(function() {
  jQuery("#datepicker1").datepicker(jQuery.datepicker.regional.fr);
});

// queue #2 - jquery cycle2 plugin and tile effect plugin
var d2 = loadScripts([
  "https://cdn.rawgit.com/malsup/cycle2/2.1.6/build/jquery.cycle2.min.js",
  "https://cdn.rawgit.com/malsup/cycle2/2.1.6/build/plugin/jquery.cycle2.tile.min.js"

]).done(function() {
  jQuery("#slideshow1").cycle({
    fx: "tileBlind",
    log: false
  });
});

// trigger a callback when all queues are complete
jQuery.when(d1, d2).done(function() {
  console.log("All scripts loaded");
});
@import url("https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/blitzer/jquery-ui.min.css");

#slideshow1 {
  position: relative;
  z-index: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<p><input id="datepicker1"></p>

<div id="slideshow1">
  <img src="https://dummyimage.com/300x100/FC0/000">
  <img src="https://dummyimage.com/300x100/0CF/000">
  <img src="https://dummyimage.com/300x100/CF0/000">
</div>

두 대기열의 스크립트는 동시에 다운로드되지만 각 대기열의 스크립트는 순서대로 다운로드되므로 순서대로 실행됩니다.폭포수 차트:

waterfall chart of scripts

yepnope.js 또는 Modernizr(yepnope.js 포함)을 사용합니다.Modernizr.load).

갱신하다

다음은 여러 스크립트에 대한 종속성을 보여주는 yepno를 사용하여 현재 사용 중인 것과 동등한 수준입니다.

yepnope({
  load: ['script1.js', 'script2.js', 'script3.js'],
  complete: function () {
      // all the scripts have loaded, do whatever you want here
  }
});

크로스 도메인이 완벽하게 작동하는 반면, Ajax에 의해 성공적으로 로드된 후 스크립트의 동일한 도메인 핫 로딩이 실제로 실행되지 않는 문제(최소한 크롬에서는)를 포함하여 멀티 스크립트 로딩과 관련된 여러 문제에 부딪혔습니다! :(

원래 질문에 대한 선택한 답변이 안정적으로 작동하지 않습니다.

여러 번 반복한 끝에 스크립트를 가져오고 스크립트별 로드 콜백 옵션과 완료 시 전체 콜백을 사용하여 특정 엄격한 순서로 여러 스크립트를 비동기식으로 로드하는 최종 답변이 여기에 있습니다. jQuery 2.1+ 및 최신 버전의 Chrome, Firefox 및 포기된 Internet Explorer에서 테스트되었습니다.

제 테스트 케이스는 3개의 파일을 로드하는 것이었습니다.그런 다음 JS webGL 렌더는 onComplete로 익명 함수 호출에 전달된 간격 검사를 사용하여 SREW 글로벌이 사용 가능해지면 렌더 스크립트를 시작합니다.

프로토타입 함수(getScripts)

function getScripts( scripts, onScript, onComplete )
{
    this.async = true;
    this.cache = false;
    this.data = null;
    this.complete = function () { $.scriptHandler.loaded(); };
    this.scripts = scripts;
    this.onScript = onScript;
    this.onComplete = onComplete;
    this.total = scripts.length;
    this.progress = 0;
};

getScripts.prototype.fetch = function() {
    $.scriptHandler = this;
    var src = this.scripts[ this.progress ];
    console.log('%cFetching %s','color:#ffbc2e;', src);

    $.ajax({
        crossDomain:true,
        async:this.async,
        cache:this.cache,
        type:'GET',
        url: src,
        data:this.data,
        statusCode: {
            200: this.complete
        },
        dataType:'script'
    });
};

getScripts.prototype.loaded = function () {
    this.progress++;
    if( this.progress >= this.total ) {
        if(this.onComplete) this.onComplete();
    } else {
        this.fetch();
    };
    if(this.onScript) this.onScript();
};

사용방법

var scripts = new getScripts(
    ['script1.js','script2.js','script.js'],
    function() {
        /* Optional - Executed each time a script has loaded (Use for Progress updates?) */
    },
    function () {
        /* Optional - Executed when the entire list of scripts has been loaded */
    }
);
scripts.fetch();

기능은 100% 신뢰할 수 없는 테스트에서 지연됨(현재는 사용되지 않음), When, Success & Complete를 사용하여 찾은 그대로입니다!?,따라서 이 기능과 statusCode를 예로 들 수 있습니다.

원하는 경우 오류/실패 처리 동작을 추가할 수 있습니다.

당신은 그것을 이용할 수 있습니다.$.when- 다음 - .

function loadScripts(scripts) {
  scripts.forEach(function (item, i) {
    item = $.getScript(item);
  });
  return $.when.apply($, scripts);
}

이 기능은 다음과 같이 사용됩니다.

loadScripts(['path/to/script-a.js', 'path/to/script-b.js']).done(function (respA, respB) {
    // both scripts are loaded; do something funny
});

그것이 약속을 사용하는 방법이며 최소한의 간접비를 사용하는 방법입니다.

좋은 대답이야, 아데노.

코드 정의 스크립트 배열을 로드할 수 있도록 답변을 보다 일반적으로 만드는 방법을 찾는 데 시간이 조금 걸렸습니다.모든 스크립트가 로드되고 실행되면 콜백이 호출됩니다.제 솔루션은 다음과 같습니다.

    function loadMultipleScripts(scripts, callback){
        var array = [];

        scripts.forEach(function(script){
            array.push($.getScript( script ))
        });

        array.push($.Deferred(function( deferred ){
                    $( deferred.resolve );
                }));

        $.when.apply($, array).done(function(){
                if (callback){
                    callback();
                }
            });
    }

async=false로 스크립트 추가

여기 다르지만 아주 간단한 접근법이 있습니다.여러 스크립트를 로드하려면 스크립트를 본문에 추가하기만 하면 됩니다.

  • 브라우저가 페이지 로드를 최적화하는 방법이기 때문에 비동기식으로 로드합니다.
  • 브라우저가 HTML 태그를 구문 분석하는 방식이기 때문에 스크립트를 순서대로 실행합니다.
  • 스크립트가 순서대로 실행되므로 콜백할 필요가 없습니다.다른 스크립트를 추가하기만 하면 다른 스크립트 다음에 실행됩니다.

자세한 내용은 https://www.html5rocks.com/en/tutorials/speed/script-loading/ 에서 확인할 수 있습니다.

var scriptsToLoad = [
   "script1.js", 
   "script2.js",
   "script3.js",
]; 
    
scriptsToLoad.forEach(function(src) {
  var script = document.createElement('script');
  script.src = src;
  script.async = false;
  document.body.appendChild(script);
});

을 사용하여 Maciej Sawicki를 입니다.Promise콜백으로:

function loadScripts(urls, path) {
    return new Promise(function(resolve) {
        urls.forEach(function(src, i) {

            let script = document.createElement('script');        
            script.type = 'text/javascript';
            script.src = (path || "") + src;
            script.async = false;

            // If last script, bind the callback event to resolve
            if(i == urls.length-1) {                    
                // Multiple binding for browser compatibility
                script.onreadystatechange = resolve;
                script.onload = resolve;
            }

            // Fire the loading
            document.body.appendChild(script);
        });
    });
}

사용:

let JSDependencies = ["jquery.js",
                      "LibraryNeedingJquery.js",
                      "ParametersNeedingLibrary.js"];

loadScripts(JSDependencies,'JavaScript/').then(taskNeedingParameters);

모든 Javascript 파일은 가능한 한 빨리 다운로드되어 주어진 순서대로 실행됩니다.그리고나서taskNeedingParameters이 호출됩니다.

찾고 있는 것은 AMD 호환 로더(require.js 등)입니다.

http://requirejs.org/

http://requirejs.org/docs/whyamd.html

찾아보면 좋은 오픈소스가 많이 있습니다.기본적으로 이를 통해 코드 모듈을 정의할 수 있으며, 다른 코드 모듈에 종속된 경우 해당 모듈이 다운로드를 완료할 때까지 기다렸다가 실행을 계속합니다.이렇게 하면 10개의 모듈을 비동기식으로 로드할 수 있으며, 한 모듈이 실행할 다른 모듈에 의존하더라도 문제가 없습니다.

이 기능은 종속성 파일이 완전히 로드된 후 파일이 로드되도록 합니다.다른 파일에 대한 종속성을 염두에 두고 파일을 순서대로 제공하면 됩니다.

function loadFiles(files, fn) {
    if (!files.length) {
        files = [];
    }
    var head = document.head || document.getElementsByTagName('head')[0];

    function loadFile(index) {
        if (files.length > index) {
            var fileref = document.createElement('script');
            fileref.setAttribute("type", "text/javascript");
            fileref.setAttribute("src", files[index]);
            head.appendChild(fileref);
            index = index + 1;
            // Used to call a callback function
            fileref.onload = function () {
                loadFile(index);
            }
        } else if(fn){
            fn();
        }
    }
    loadFile(0);
}

이것은 나에게 도움이 됩니다.

function getScripts(scripts) {
    var prArr = [];
    scripts.forEach(function(script) { 
        (function(script){
            prArr .push(new Promise(function(resolve){
                $.getScript(script, function () {
                    resolve();
                });
            }));
        })(script);
    });
    return Promise.all(prArr, function(){
        return true;
    });
}

사용:

var jsarr = ['script1.js','script2.js'];
getScripts(jsarr).then(function(){
...
});

위의 앤드류 마크 뉴턴의 포괄적인 답변의 짧은 버전.정의되지 않은 UI 동작을 방지하기 위해 수행해야 하는 상태 코드를 확인하지 않습니다.

이것은 제가 jQuery를 보증할 수 있지만 다른 것은 포함하지 않는 성가신 시스템을 위한 것이었습니다. 그래서 저는 외부 스크립트에 강제로 입력되지 않을 정도로 짧은 기술을 원했습니다. (색인 0을 첫 번째 "재귀적" 호출에 전달함으로써 더 짧게 만들 수 있었지만 스타일 습관의 힘이 제게 설탕을 추가하게 했습니다.)

또한 종속성 목록을 모듈 이름에 할당하여 이 블록을 "module1"이 필요한 곳에 포함할 수 있으며 스크립트 및 종속 초기화는 한 번만 포함/실행됩니다(로그할 수 있음).index콜백에서 실행 중인 단일 주문 AJAX 요청 집합 확인)

if(typeof(__loaders) == 'undefined') __loaders = {};

if(typeof(__loaders.module1) == 'undefined')
{
    __loaders.module1 = false;

    var dependencies = [];

    dependencies.push('/scripts/loadmefirst.js');
    dependencies.push('/scripts/loadmenext.js');
    dependencies.push('/scripts/loadmelast.js');

    var getScriptChain  = function(chain, index)        
    {
        if(typeof(index) == 'undefined')
            index = 0;

        $.getScript(chain[index], 
            function()
            {
                if(index == chain.length - 1)
                {
                    __loaders.module1 = true;

                    /* !!!
                        Do your initialization of dependent stuff here 
                    !!! */
                }
                else 
                    getScriptChain(chain, index + 1);
            }
        );
    };

    getScriptChain(dependencies);       
}

jQuery의 getScript 메서드를 확장하는 플러그인이 있습니다.비동기식 및 동기식 로드를 허용하고 jQuery의 캐싱 메커니즘을 사용합니다.완전 공개, 제가 쓴 거예요더 좋은 방법을 찾으시면 부담없이 기부해주세요.

https://github.com/hudsonfoo/jquery-getscripts

n개의 스크립트를 하나씩 로드합니다(예: 두 번째 파일에 첫 번째 파일이 필요한 경우 유용).

(function self(a,cb,i){
    i = i || 0; 
    cb = cb || function(){};    
    if(i==a.length)return cb();
    $.getScript(a[i++],self.bind(0,a,cb,i));                    
})(['list','of','script','urls'],function(){console.log('done')});

위의 @adeneo의 답변에 기초하여: css 파일과 js 파일의 로딩을 모두 결합합니다.

개선을 위한 제안이 있습니까?

// Usage
//$.getMultiResources(['script-1.js','style-1.css'], 'assets/somePath/')
//  .done(function () {})
//  .fail(function (error) {})
//  .always(function () {});

(function ($) {
  $.getMultiResources = function (arr, pathOptional, cache) {
    cache = (typeof cache === 'undefined') ? true : cache;
    var _arr = $.map(arr, function (src) {
      var srcpath = (pathOptional || '') + src;
      if (/.css$/i.test(srcpath)) {
        return $.ajax({
          type: 'GET',
          url: srcpath,
          dataType: 'text',
          cache: cache,
          success: function () {
            $('<link>', {
              rel: 'stylesheet',
              type: 'text/css',
              'href': srcpath
            }).appendTo('head');
          }
        });

      } else {
        return $.ajax({
          type: 'GET',
          url: srcpath,
          dataType: 'script',
          cache: cache
        });
      }
    });
    //
    _arr.push($.Deferred(function (deferred) {
      $(deferred.resolve);
    }));
    //
    return $.when.apply($, _arr);
  };
})(jQuery);

재귀를 사용하여 시도해 볼 수 있습니다.그러면 전체 목록 다운로드가 완료될 때까지 동기화된 상태로 차례로 다운로드됩니다.

var queue = ['url/links/go/here'];

ProcessScripts(function() { // All done do what ever you want

}, 0);

function ProcessScripts(cb, index) {
    getScript(queue[index], function() {
        index++;
        if (index === queue.length) { // Reached the end
            cb();
        } else {
            return ProcessScripts(cb, index);
        }
    });
}

function getScript(script, callback) {
    $.getScript(script, function() {
        callback();
    });
}

@adeneo 스크립트가 개선되어 모든 스크립트가 지정된 순서로 로드됩니다.체인 로딩을 하지 않아 매우 빠르지만, 더 빠른 것을 원한다면 50ms 대기 시간을 변경하십시오.

$.getMultiScripts = function(arr, path) {

    function executeInOrder(scr, code, resolve) {
        // if its the first script that should be executed
        if (scr == arr[0]) {
            arr.shift();
            eval(code);
            resolve();
            console.log('executed', scr);
        } else {
            // waiting
            setTimeout(function(){
                executeInOrder(scr, code, resolve);
            }, 50);
        }
    }

    var _arr = $.map(arr, function(scr) {

        return new Promise((resolve) => {
            jQuery.ajax({
                type: "GET",
                url: (path || '') + scr,
                dataType: "text",
                success: function(code) {
                    console.log('loaded  ', scr);
                    executeInOrder(scr, code, resolve);
                },
                cache: true
            });
        });

    });
        
    _arr.push($.Deferred(function( deferred ){
        $( deferred.resolve );
    }));
        
    return $.when.apply($, _arr);
}

사용법은 동일합니다.

var script_arr = [
    'myscript1.js', 
    'myscript2.js', 
    'myscript3.js'
];

$.getMultiScripts(script_arr, '/mypath/').done(function() {
    // all scripts loaded
});

언급URL : https://stackoverflow.com/questions/11803215/how-to-include-multiple-js-files-using-jquery-getscript-method