복붙노트

[JQUERY] 동적 내부 JS JS로드 [중복]

JQUERY

동적 내부 JS JS로드 [중복]

해결법


  1. 1.내가처럼 내 자신의 구현을 사용하므로 jQuery의 $ .getScript는 (), 버그 때때로 :

    내가처럼 내 자신의 구현을 사용하므로 jQuery의 $ .getScript는 (), 버그 때때로 :

    jQuery.loadScript = function (url, callback) {
        jQuery.ajax({
            url: url,
            dataType: 'script',
            success: callback,
            async: true
        });
    }
    

    그것을 같이 사용 :

    if (typeof someObject == 'undefined') $.loadScript('url_to_someScript.js', function(){
        //Stuff to do after someScript has loaded
    });
    

  2. 2.내 생각 엔 당신의 DOM 전용 솔루션에 당신이 좋아하는 일을 한 것입니다 :

    내 생각 엔 당신의 DOM 전용 솔루션에 당신이 좋아하는 일을 한 것입니다 :

    var script = document.createElement('script');
    script.src = something;
    //do stuff with the script
    

    가로드되지 않도록 스크립트, 문서 트리에 추가되지 않습니다하지 작업 때문에 우선,. 해당 스크립트가 완전히로드 될 때까지의 내용이 당신에게 사용할 수 없습니다, 그래서 다른 스크립트로드가있는 동안 또한, 당신이 할 경우에도, 자바 스크립트의 실행이 계속됩니다.

    당신은 스크립트의로드 이벤트를 수신, 당신이하는 것처럼 결과에 일을 할 수있다. 그래서:

    var script = document.createElement('script');
    script.onload = function () {
        //do stuff with the script
    };
    script.src = something;
    
    document.head.appendChild(script); //or something of the likes
    

  3. 3.내가 이것을 사용 그래서 나는 자주이 작업을 수행 할 필요가 :

    내가 이것을 사용 그래서 나는 자주이 작업을 수행 할 필요가 :

    var loadJS = function(url, implementationCode, location){
        //url is URL of external file, implementationCode is the code
        //to be called from the file, location is the location to 
        //insert the <script> element
    
        var scriptTag = document.createElement('script');
        scriptTag.src = url;
    
        scriptTag.onload = implementationCode;
        scriptTag.onreadystatechange = implementationCode;
    
        location.appendChild(scriptTag);
    };
    var yourCodeToBeCalled = function(){
    //your code goes here
    }
    loadJS('yourcode.js', yourCodeToBeCalled, document.body);
    

    자세한 내용은 내 기능 아이디어의 원천 또 다른 자바 스크립트 파일?에서 자바 스크립트 파일을 포함 할 방법이 사이트를 참조하십시오.


  4. 4.동적으로 페이지가 아닌 다른 JS 파일 내부에 JS를로드 할 수 있습니다

    동적으로 페이지가 아닌 다른 JS 파일 내부에 JS를로드 할 수 있습니다

    당신은 JS 파일을로드 할 getScript을 사용해야합니다

    $.getScript("ajax/test.js", function(data, textStatus, jqxhr) {
    console.log(data); //data returned
    console.log(textStatus); //success
    console.log(jqxhr.status); //200
    console.log('Load was performed.');
    });
    

  5. 5.Necromaning.

    Necromaning.

    나는 따라 스크립트를로드하려면이 옵션을 사용; 그것은 jQuery를 같은 다른 라이브러리에 종속성을 추가하지 않고 IE8 +와 함께 작동합니다!

    var cScriptLoader = (function ()
    {
        function cScriptLoader(files)
        {
            var _this = this;
            this.log = function (t)
            {
                console.log("ScriptLoader: " + t);
            };
            this.withNoCache = function (filename)
            {
                if (filename.indexOf("?") === -1)
                    filename += "?no_cache=" + new Date().getTime();
                else
                    filename += "&no_cache=" + new Date().getTime();
                return filename;
            };
            this.loadStyle = function (filename)
            {
                // HTMLLinkElement
                var link = document.createElement("link");
                link.rel = "stylesheet";
                link.type = "text/css";
                link.href = _this.withNoCache(filename);
                _this.log('Loading style ' + filename);
                link.onload = function ()
                {
                    _this.log('Loaded style "' + filename + '".');
                };
                link.onerror = function ()
                {
                    _this.log('Error loading style "' + filename + '".');
                };
                _this.m_head.appendChild(link);
            };
            this.loadScript = function (i)
            {
                var script = document.createElement('script');
                script.type = 'text/javascript';
                script.src = _this.withNoCache(_this.m_js_files[i]);
                var loadNextScript = function ()
                {
                    if (i + 1 < _this.m_js_files.length)
                    {
                        _this.loadScript(i + 1);
                    }
                };
                script.onload = function ()
                {
                    _this.log('Loaded script "' + _this.m_js_files[i] + '".');
                    loadNextScript();
                };
                script.onerror = function ()
                {
                    _this.log('Error loading script "' + _this.m_js_files[i] + '".');
                    loadNextScript();
                };
                _this.log('Loading script "' + _this.m_js_files[i] + '".');
                _this.m_head.appendChild(script);
            };
            this.loadFiles = function ()
            {
                // this.log(this.m_css_files);
                // this.log(this.m_js_files);
                for (var i = 0; i < _this.m_css_files.length; ++i)
                    _this.loadStyle(_this.m_css_files[i]);
                _this.loadScript(0);
            };
            this.m_js_files = [];
            this.m_css_files = [];
            this.m_head = document.getElementsByTagName("head")[0];
            // this.m_head = document.head; // IE9+ only
            function endsWith(str, suffix)
            {
                if (str === null || suffix === null)
                    return false;
                return str.indexOf(suffix, str.length - suffix.length) !== -1;
            }
            for (var i = 0; i < files.length; ++i)
            {
                if (endsWith(files[i], ".css"))
                {
                    this.m_css_files.push(files[i]);
                }
                else if (endsWith(files[i], ".js"))
                {
                    this.m_js_files.push(files[i]);
                }
                else
                    this.log('Error unknown filetype "' + files[i] + '".');
            }
        }
        return cScriptLoader;
    })();
    var ScriptLoader = new cScriptLoader(["foo.css", "Scripts/Script4.js", "foobar.css", "Scripts/Script1.js", "Scripts/Script2.js", "Scripts/Script3.js"]);
    ScriptLoader.loadFiles();
    

    당신이 타이프 버전에 관심이 있다면이를 만드는 데 사용 :

    class cScriptLoader {
        private m_js_files: string[];
        private m_css_files: string[];
        private m_head:HTMLHeadElement;
    
        private log = (t:any) =>
        {
            console.log("ScriptLoader: " + t);
        }
    
    
        constructor(files: string[]) {
            this.m_js_files = [];
            this.m_css_files = [];
            this.m_head = document.getElementsByTagName("head")[0];
            // this.m_head = document.head; // IE9+ only
    
    
            function endsWith(str:string, suffix:string):boolean 
            {
                if(str === null || suffix === null)
                    return false;
    
                return str.indexOf(suffix, str.length - suffix.length) !== -1;
            }
    
    
            for(let i:number = 0; i < files.length; ++i) 
            {
                if(endsWith(files[i], ".css"))
                {
                    this.m_css_files.push(files[i]);
                }
                else if(endsWith(files[i], ".js"))
                {
                    this.m_js_files.push(files[i]);
                }
                else
                    this.log('Error unknown filetype "' + files[i] +'".');
            }
    
        }
    
    
        public withNoCache = (filename:string):string =>
        {
            if(filename.indexOf("?") === -1)
                filename += "?no_cache=" + new Date().getTime();
            else
                filename += "&no_cache=" + new Date().getTime();
    
            return filename;    
        }
    
    
        public loadStyle = (filename:string) =>
        {
            // HTMLLinkElement
            let link = document.createElement("link");
            link.rel = "stylesheet";
            link.type = "text/css";
            link.href = this.withNoCache(filename);
    
            this.log('Loading style ' + filename);
            link.onload = () =>
            {
                this.log('Loaded style "' + filename + '".');
    
            };
    
            link.onerror = () =>
            {
                this.log('Error loading style "' + filename + '".');
            };
    
            this.m_head.appendChild(link);
        }
    
    
        public loadScript = (i:number) => 
        {
            let script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = this.withNoCache(this.m_js_files[i]);
    
            var loadNextScript = () => 
            {
                if (i + 1 < this.m_js_files.length)
                {
                    this.loadScript(i + 1);
                }
            }
    
            script.onload = () =>
            {
                this.log('Loaded script "' + this.m_js_files[i] + '".');
                loadNextScript();
            };
    
    
            script.onerror = () =>
            {
                this.log('Error loading script "' + this.m_js_files[i] + '".');
                loadNextScript();
            };
    
    
            this.log('Loading script "' + this.m_js_files[i] + '".');
            this.m_head.appendChild(script);
        }
    
        public loadFiles = () => 
        {
            // this.log(this.m_css_files);
            // this.log(this.m_js_files);
    
            for(let i:number = 0; i < this.m_css_files.length; ++i)
                this.loadStyle(this.m_css_files[i])
    
            this.loadScript(0);
        }
    
    }
    
    
    var ScriptLoader = new cScriptLoader(["foo.css", "Scripts/Script4.js", "foobar.css", "Scripts/Script1.js", "Scripts/Script2.js", "Scripts/Script3.js"]);
    ScriptLoader.loadFiles();
    

    이 스크립트리스트를 동적로드의 경우, 이러한 데이터 본체, 예를 들어 같은 속성에 스크립트를 작성 <스크립트 SRC = "scriptloader.js"데이터 주 = "file1.js, file2.js, file3.js 등." > 그리고 element.getAttribute를 ( "데이터 주") 할. 분할 ( '')

    var target = document.currentScript || (function() {
      var scripts = document.getElementsByTagName('script');
      // Note: this is for IE as IE doesn't support currentScript
      // this does not work if you have deferred loading with async
      // e.g. <script src="..." async="async" ></script>
      // https://web.archive.org/web/20180618155601/https://www.w3schools.com/TAgs/att_script_async.asp
      return scripts[scripts.length - 1];
    })();
    
    target.getAttribute("data-main").split(',')
    

    목록을 얻었다.


  6. 6.jQuery.getScript () 메소드 (: $ 아약스 ({URL : URL, dataType와 "스크립트"}) 데이터 유형 속성) 아약스 기능의 속기

    jQuery.getScript () 메소드 (: $ 아약스 ({URL : URL, dataType와 "스크립트"}) 데이터 유형 속성) 아약스 기능의 속기

    당신은 스크립트를 캐시 할, 중 하나를 사용 RequireJS 수 또는 다음과 유사한 jQuery.getScript 방법 확장에 jQuery의 예를 따르십시오.

    jQuery.cachedScript = function( url, options ) {
    
      // Allow user to set any option except for dataType, cache, and url
      options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
      });
    
      // Use $.ajax() since it is more flexible than $.getScript
      // Return the jqXHR object so we can chain callbacks
      return jQuery.ajax( options );
    };
    
    // Usage
    $.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
      console.log( textStatus );
    });
    

    참조 : jQuery.getScript () | 의 jQuery API 문서


  7. 7.jQuery를가) ($ .getScript있다 :

    jQuery를가) ($ .getScript있다 :


  8. 8.당신은 jQuery를 사용하여 그것을 할 수 있습니다 :

    당신은 jQuery를 사용하여 그것을 할 수 있습니다 :

    $.getScript("ajax/test.js", function(data, textStatus, jqxhr) {
      console.log(data); //data returned
      console.log(textStatus); //success
      console.log(jqxhr.status); //200
      console.log('Load was performed.');
    });
    

    이 링크는 도움이 될 것입니다 : http://api.jquery.com/jQuery.getScript/


  9. 9.나는 AMD 자바 스크립트 클래스 파일로 requirejs 사용을 권장하고 있습니다

    나는 AMD 자바 스크립트 클래스 파일로 requirejs 사용을 권장하고 있습니다

    여기를 사용하는 방법의 좋은 예

    http://www.sitepoint.com/understanding-requirejs-for-effective-javascript-module-loading/


  10. 10.내 플러그인을 제작하기 전 미리 정의 된 모두의 JS 파일 내의 외부 스크립트와 스타일을로드 할 필요가 있었다. 이를 위해, 나는 다음을했다 :

    내 플러그인을 제작하기 전 미리 정의 된 모두의 JS 파일 내의 외부 스크립트와 스타일을로드 할 필요가 있었다. 이를 위해, 나는 다음을했다 :

        this.loadRequiredFiles = function (callback) {
            var scripts = ['xx.js', 'yy.js'];
            var styles = ['zz.css'];
            var filesloaded = 0;
            var filestoload = scripts.length + styles.length;
            for (var i = 0; i < scripts.length; i++) {
                log('Loading script ' + scripts[i]);
                var script = document.createElement('script');
                script.type = 'text/javascript';
                script.src = scripts[i];
                script.onload = function () {
                    log('Loaded script');
                    log(this);
                    filesloaded++;  // (This means increment, i.e. add one)
                    finishLoad();
                };
                document.head.appendChild(script);
            }
            for (var i = 0; i < styles.length; i++) {
                log('Loading style ' + styles[i]);
                var style = document.createElement('link');
                style.rel = 'stylesheet';
                style.href = styles[i];
                style.type = 'text/css';
                style.onload = function () {
                    log('Loaded style');
                    log(this);
                    filesloaded++;
                    finishLoad();
                };
                document.head.appendChild(style);
            }
            function finishLoad() {
                if (filesloaded === filestoload) {
                    callback();
                }
            }
        };
    

    컨텍스트에서 스크립트의 더 많은 :

    function myPlugin() {
    
        var opts = {
            verbose: false
        };                          ///< The options required to run this function
        var self = this;            ///< An alias to 'this' in case we're in jQuery                         ///< Constants required for this function to work
    
        this.getOptions = function() {
            return opts;
        };
    
        this.setOptions = function(options) {
            for (var x in options) {
                opts[x] = options[x];
            }
        };
    
        /**
         * @brief Load the required files for this plugin
         * @param {Function} callback A callback function to run when all files have been loaded
         */
        this.loadRequiredFiles = function (callback) {
            var scripts = ['xx.js', 'yy.js'];
            var styles = ['zz.css'];
            var filesloaded = 0;
            var filestoload = scripts.length + styles.length;
            for (var i = 0; i < scripts.length; i++) {
                log('Loading script ' + scripts[i]);
                var script = document.createElement('script');
                script.type = 'text/javascript';
                script.src = scripts[i];
                script.onload = function () {
                    log('Loaded script');
                    log(this);
                    filesloaded++;
                    finishLoad();
                };
                document.head.appendChild(script);
            }
            for (var i = 0; i < styles.length; i++) {
                log('Loading style ' + styles[i]);
                var style = document.createElement('link');
                style.rel = 'stylesheet';
                style.href = styles[i];
                style.type = 'text/css';
                style.onload = function () {
                    log('Loaded style');
                    log(this);
                    filesloaded++;
                    finishLoad();
                };
                document.head.appendChild(style);
            }
            function finishLoad() {
                if (filesloaded === filestoload) {
                    callback();
                }
            }
        };
    
        /**
         * @brief Enable user-controlled logging within this function
         * @param {String} msg The message to log
         * @param {Boolean} force True to log message even if user has set logging to false
         */
        function log(msg, force) {
            if (opts.verbose || force) {
                console.log(msg);
            }
        }
    
        /**
         * @brief Initialise this function
         */
        this.init = function() {
            self.loadRequiredFiles(self.afterLoadRequiredFiles);
        };
    
        this.afterLoadRequiredFiles = function () {
            // Do stuff
        };
    
    }
    

  11. 11.당신은 그것을 할 jQuery의 $ .getScript () 메소드를 사용할 수 있지만 좀 더 전체 기능을 원하는 경우, yepnope.js 당신의 선택입니다. 이 스크립트와 스타일 시트의 조건 로딩을 지원하고 사용하기 쉽습니다.

    당신은 그것을 할 jQuery의 $ .getScript () 메소드를 사용할 수 있지만 좀 더 전체 기능을 원하는 경우, yepnope.js 당신의 선택입니다. 이 스크립트와 스타일 시트의 조건 로딩을 지원하고 사용하기 쉽습니다.


  12. 12.여기에 부하 자바 스크립트와 CSS에 약간의 LIB 동적 파일은 다음과 같다 :

    여기에 부하 자바 스크립트와 CSS에 약간의 LIB 동적 파일은 다음과 같다 :

    https://github.com/todotresde/javascript-loader

    내가 추측 부하 CSS와 JS 파일에 유용한 순서로 동적입니다.

    지원 단지의 주요 파일을 원하는 lib 디렉토리를로드, 확장,하지, 당신은 사용자 정의 파일을로드하는 데 사용할 수 있습니다.

    즉. :

    <html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="scripts/javascript-loader.js" type="text/javascript" charset="utf-8" ></script>    
        <script type="text/javascript">
            $(function() {
    
                registerLib("threejs", test);
    
                function test(){
                    console.log(THREE);
                }
    
                registerLib("tinymce", draw);
    
                function draw(){
                    tinymce.init({selector:'textarea'});
                }
    
            }); 
        </script>
    </head>
    <body>
        <textarea>Your content here.</textarea>
    </body>
    

  13. 13.당신이 종속 많은 파일이있는 경우, AMD / RequireJS를 사용합니다. http://requirejs.org/

    당신이 종속 많은 파일이있는 경우, AMD / RequireJS를 사용합니다. http://requirejs.org/

  14. from https://stackoverflow.com/questions/14521108/dynamically-load-js-inside-js by cc-by-sa and MIT license