Javascript run inline script after load async resources

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.


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>

Tags:

Javascript