Javascript run inline script after load async resources

后端 未结 2 758
伪装坚强ぢ
伪装坚强ぢ 2020-12-18 04:42

when I test page by optimizer, it suggest me use async for all CDN sources what I use.

To run any script I use

(function(){})();

I use a

相关标签:
2条回答
  • 2020-12-18 05:33

    If I understood your problem correctly, you want to run inline script when the async script tag is loaded.

    You can use onload event of the script tag.

    function runInline() {
      console.log('inline script run')
    }
    <script async src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" onload="runInline()"></script>

    0 讨论(0)
  • 2020-12-18 05:40

    Wrapping your code in:

    (function () {
    })();
    

    ... does not delay its execution. To delay your script until resources have been loaded, wait to the window load event:

    The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.

    Here is an example that loads jQuery with a <script async> element, and shows the jQuery version via the inline script:

    window.addEventListener('load', function () {
        console.log(jQuery.fn.jquery);
    });
    <script async src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    To capture the event when a particular async script has been loaded, you could listen to its own load event. For that to work it is probably the easiest if you give an id to the script element of your interest, and make sure the inline code comes after it:

    jq.addEventListener('load', function () {
        console.log(jQuery.fn.jquery);
    });
    <script id="jq" async src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    Note that the async (and defer) attributes have no effect on inline scripts:

    The defer and async attributes must not be specified if the src attribute is not present.

    They only have an effect on script elements that have the src attribute.

    0 讨论(0)
提交回复
热议问题