Program Tip

jQuery 로딩을 연기 할 수 있습니까?

programtip 2020. 11. 18. 09:41
반응형

jQuery 로딩을 연기 할 수 있습니까?


현실을 직시하자, jQuery / jQuery-ui는 많은 다운로드입니다.

Google 초기 렌더링 속도를 높이기 위해 자바 스크립트 지연로드를 권장 합니다. 내 페이지는 jQuery를 사용하여 페이지의 낮은 위치 (대부분 초기보기에서 벗어남)에 배치되는 탭을 설정하고 페이지가 렌더링 된 후 jQuery를 연기하고 싶습니다.

Google의 지연 코드는 페이지가로드 된 후 body onLoad 이벤트에 연결하여 DOM에 태그를 추가합니다.

<script type="text/javascript">

 // Add a script element as a child of the body
 function downloadJSAtOnload() {
 var element = document.createElement("script");
 element.src = "deferredfunctions.js";
 document.body.appendChild(element);
 }

 // Check for browser support of event handling capability
 if (window.addEventListener)
 window.addEventListener("load", downloadJSAtOnload, false);
 else if (window.attachEvent)
 window.attachEvent("onload", downloadJSAtOnload);
 else window.onload = downloadJSAtOnload;

</script>

이런 식으로 jQuery로드를 연기하고 싶지만 시도했을 때 jQuery 코드가 jQuery를 찾지 못했습니다 (내가 전혀 예상하지 못한 것은 아닙니다).

$(document).ready(function() {
    $("#tabs").tabs();
});

따라서 jQuery가로드 될 때까지 jQuery 코드 실행을 연기하는 방법을 찾아야하는 것 같습니다. 추가 된 태그가로드 및 구문 분석을 완료했는지 어떻게 감지합니까?

결과적으로 비동기 로딩 에도 답변이 포함될 수 있습니다.

이견있는 사람?


이것은 jQuerify 북마크릿에서 얼마 전에 편집 한 것입니다. jQuery를로드하고로드 된 후 항목을 실행하는 데 자주 사용합니다. 물론 거기에서 URL을 사용자 정의 jquery에 대한 자체 URL로 바꿀 수 있습니다.

(function() {
      function getScript(url,success){
        var script=document.createElement('script');
        script.src=url;
        var head=document.getElementsByTagName('head')[0],
            done=false;
        script.onload=script.onreadystatechange = function(){
          if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {
            done=true;
            success();
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
          }
        };
        head.appendChild(script);
      }
        getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js',function(){
            // YOUR CODE GOES HERE AND IS EXECUTED AFTER JQUERY LOADS
        });
    })();

실제로 jQuery와 jQuery-UI를 하나의 파일로 결합하고 URL을 사용합니다. 개별적으로로드하려면 getScript를 연결하면됩니다.

getScript('http://myurltojquery.js',function(){
        getScript('http://myurltojqueryUI.js',function(){
              //your tab code here
        })
});

이것은 중요한 주제에 대한 최고 순위 질문이므로 @valmarv 및 @amparsand의 이전 답변을 기반으로 이에 대한 내 의견을 제공 할 수 있도록 대담하게 설명하겠습니다.

스크립트를로드하기 위해 다차원 배열을 사용하고 있습니다. 그들 사이에 종속성이없는 그룹화 :

var dfLoadStatus = 0;
var dfLoadFiles = [
      ["http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"],
      ["http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js",
       "/js/somespecial.js",
       "/js/feedback-widget.js#2312195",
       "/js/nohover.js"]
     ];

function downloadJSAtOnload() {
    if (!dfLoadFiles.length) return;

    var dfGroup = dfLoadFiles.shift();
    dfLoadStatus = 0;

    for(var i = 0; i<dfGroup.length; i++) {
        dfLoadStatus++;
        var element = document.createElement('script');
        element.src = dfGroup[i];
        element.onload = element.onreadystatechange = function() {
        if ( ! this.readyState || 
               this.readyState == 'complete') {
            dfLoadStatus--;
            if (dfLoadStatus==0) downloadJSAtOnload();
        }
    };
    document.body.appendChild(element);
  }

}

if (window.addEventListener)
    window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
    window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;

로드 된 후 첫 번째 jquery를로드하고 한 번에 다른 스크립트를 계속로드합니다. 페이지 어디에서나 배열에 추가하여 스크립트를 쉽게 추가 할 수 있습니다.

dfLoadFiles.push(["/js/loadbeforeA.js"]);
dfLoadFiles.push(["/js/javascriptA.js", "/js/javascriptB.js"]);
dfLoadFiles.push(["/js/loadafterB.js"]);

다음은 async / defer javascript loading에 대한 현대적인 접근 방식에 대한 좋은 설명입니다 . 그러나 인라인 스크립트에서는 작동하지 않습니다.

<script type="text/javascript" src="/jquery/3.1.1-1/jquery.min.js" defer></script>
<script type="text/javascript" defer>
    $(function () {   //  <- jquery is not yet initialized
      ...
    });
</script>

비동기 로딩에 대한 가장 간단한 솔루션은 @nilskp-externalize 스크립트에 의해 제안되었습니다.

<script type="text/javascript" src="/jquery/3.1.1-1/jquery.min.js" defer></script>
<script type="text/javascript" src="resources/js/onload.js" defer></script>

HTML 파일 끝에 jQuery 및 jQuery 종속 코드를 넣으십시오.

편집 : 조금 더 명확하게

<html>
<head></head>
<body>
    <!-- Your normal content here -->
    <script type="text/javascript" src="http://path/to/jquery/jquery.min.js"></script>
    <script>//Put your jQuery code here</script>
</body>
</html>

element.addEventListener("load", function () {
    $('#tabs').tabs()
}, false);

그것을 시도하십시오.


특정 상황에서 jquery가로드 될 때 이벤트를 발생시킬 수 있습니다.

<script type="text/javascript">
    (function (window) {

        window.jQueryHasLoaded = false;

        document.body.addEventListener('jqueryloaded', function (e) {
            console.log('jqueryloaded ' + new Date() );
        }, false);

        function appendScript(script) {
            var tagS = document.createElement("script"), 
                s = document.getElementsByTagName("script")[0];
            tagS.src = script.src;
            s.parentNode.insertBefore(tagS, s);

            if ( script.id == 'jquery' ) {
                tagS.addEventListener('load', function (e) {
                    window.jQueryHasLoaded = true;
                    var jQueryLoaded = new Event('jqueryloaded');
                    document.body.dispatchEvent(jQueryLoaded);
                }, false);
            }
        }

        var scripts = [
            {
                'id': 'jquery',
                'src': 'js/libs/jquery/jquery-2.0.3.min.js'
            },
            {
                'src': 'js/myscript1.js'
            },
            {
                'src': 'js/myscript2.js'
            }
        ];

        for (var i=0; i < scripts.length; i++) {
            appendScript(scripts[i]);
        }

    }(window));
</script>

그런 다음 종속성을 함수로 래핑합니다.

// myscript1.js 
(function(){ 

    function initMyjQueryDependency() {
        console.log('my code is executed after jquery is loaded!');
        // here my code that depends on jquery
    }

    if ( jQueryHasLoaded === true )
        initMyjQueryDependency();
    else
        document.body.addEventListener('jqueryloaded', initMyjQueryDependency, false);

}());

jquery가 다른 스크립트 이후에로드를 마치면 jqueryloaded 이벤트가 시작될 때 종속성이 실행됩니다.

jquery가 이미로드 된 경우 jQueryHasLoaded === true종속성이 실행 initMyjQueryDependency()됩니다.


async / defered jquery 스크립트 태그 뒤에이 코드를 추가합니다.이 코드는 모든로드가 완료 될 때 실행해야하는 모든 항목을 누적하는 임시 함수 $를 정의한 다음,이 시간까지 $를 사용합니다. 기능을 실행하기 위해 덮어 쓰여집니다. 이 코드를 사용하면 문서에서 더 아래에있는 jQuery onload 구문을 변경할 필요가 없습니다.

<script defer async src="https://code.jquery.com/jquery-2.2.0.min.js">
<script>
    var executeLater = [];
    function $(func) {
        executeLater.push(func);
    }
    window.addEventListener('load', function () {
        $(function () {
            for (var c = 0; c < executeLater.length; c++) {
                executeLater[c]();
            }
        });
    })
</script>

....그리고...

<script>
    $(function() {
        alert("loaded");
    });
</script>

글쎄, 당신이해야 할 일은 a)로드시 실행하려는 jQuery 코드를 jQuery 파일의 끝에 추가하거나 b) downloadJSAtOnload다음과 같이 함수에 추가하는 것입니다.

<script type="text/javascript">

 // Add a script element as a child of the body
 function downloadJSAtOnload() {
 var element = document.createElement("script");
 element.src = "deferredfunctions.js";
 document.body.appendChild(element);
 $("#tabs").tabs(); // <==== NOTE THIS. This should theoretically run after the
                    // script has been appended, though you'll have to test this
                    // because I don't know if the JavaScript above will wait for
                    // the script to load before continuing
 }

 // Check for browser support of event handling capability
 if (window.addEventListener)
 window.addEventListener("load", downloadJSAtOnload, false);
 else if (window.attachEvent)
 window.attachEvent("onload", downloadJSAtOnload);
 else window.onload = downloadJSAtOnload;

</script>

다음 코드는 창로드가 완료된 후 스크립트를로드해야합니다.

<html>
<head>
    <script>
    var jQueryLoaded = false;
    function test() {
        var myScript = document.createElement('script');
        myScript.type = 'text/javascript';
        myScript.async = true;
        myScript.src = jQueryLoaded ? 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js' : 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js';
        document.body.appendChild(myScript);

        if(!jQueryLoaded){
            alert('jquery was loaded');
            jQueryLoaded = true;
            test();
        } else {
            alert('jqueryui was loaded');   
        }
    }

    if (window.addEventListener){
        alert('window.addEventListener');
        window.addEventListener("load", test, false);
    } else if (window.attachEvent){
        alert('window.attachEvent');
        window.attachEvent("onload", test);
    } else{
        alert('window.onload');
        window.onload = test;
    }
    </script>
</head>
<body>
<p>Placeholder text goes here</p>
</body>
</html>

Chrome, FF 및 IE9에서 저를 위해 일했습니다. 도움이되는지 알려주세요.


Here's my version which supports chaining to be sure the scripts are loaded one after each other, based on ampersand's code:

var deferredJSFiles = ['jquery/jquery', 'file1', 'file2', 'file3'];
function downloadJSAtOnload() {
    if (!deferredJSFiles.length)
        return;
    var deferredJSFile = deferredJSFiles.shift();
    var element = document.createElement('script');
    element.src = deferredJSFile.indexOf('http') == 0 ? deferredJSFile : '/js/' + deferredJSFile + '.js';
    element.onload = element.onreadystatechange = function() {
        if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')
            downloadJSAtOnload();
    };
    document.body.appendChild(element);
}
if (window.addEventListener)
    window.addEventListener('load', downloadJSAtOnload, false);
else if (window.attachEvent)
    window.attachEvent('onload', downloadJSAtOnload);
else
    window.onload = downloadJSAtOnload;

<!doctype html>
<html>
    <head>

    </head>
    <body>
        <p>If you click on the "Hide" button, I will disappear.</p>
        <button id="hide" >Hide</button>
        <button id="show" >Show</button>

        <script type="text/javascript">
            function loadScript(url, callback) {

                var script = document.createElement("script")
                script.type = "text/javascript";

                if (script.readyState) {  //IE
                    script.onreadystatechange = function() {
                        if (script.readyState == "loaded" ||
                                script.readyState == "complete") {
                            script.onreadystatechange = null;
                            callback();
                        }
                    };
                } else {  //Others
                    script.onload = function() {
                        callback();
                    };
                }

                script.src = url;
                document.body.appendChild(script);
            }
            loadScript("http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js",
                    function() {
                        //YAHOO.namespace("mystuff");
                        $("#show").click(function() {
                            $("p").show();
                        });
                        $("#hide").click(function() {
                            $("p").hide();
                        });

                        //more...
                    });
        </script>

    </body>
</html>

I think Modernizr.load() is worth a mention here - it handles dependency loading very nicely


Appears that you just need <script defer> : http://www.w3schools.com/tags/att_script_defer.asp


Take a look jQuery.holdReady()

"Holds or releases the execution of jQuery's ready event." (jQuery 1.6+)

http://api.jquery.com/jQuery.holdReady/


Load all scripts at the end of html with http://labjs.com, it is 100% solution and I tested it many times against gtmetrix rules. example http://gtmetrix.com/reports/interactio.cz/jxomHSLV

참고URL : https://stackoverflow.com/questions/5852767/possible-to-defer-loading-of-jquery

반응형