Does the attribute "async" serve to execute dynamically loaded scripts? (AJAX)

Asked

Viewed 937 times

1

I have a problem with content loaded in AJAX.

Is the following: when I load scripts via ajax, I don’t have the events "onload" or similar to trigger the loaded script. The attribute async on the tag script solves this? If not, how can I solve this problem? (How can I fire dynamically loaded scripts?)

UPDATE

I expressed myself badly in the question and ended up not reflecting my real doubt. I apologize to those who invested their time in answering. I tried to erase the question, but I couldn’t.

PS: I have solved the problem. Thank you all.

  • Can you explain better what you mean by "load scripts via ajax"? You directly upload a JS file/code, or is it an HTML tag <script src="..."> within?

3 answers

6


Not, the use of the attribute async in elements <script src="..."> is to avoid the render lock (blocking-render).

About using Ajax I really do not think it is necessary so much work, can rather load the script dynamically with document.createElement, it is not even necessary to async, however it is good to use it, at the end of the answer has an example of how to load dynamically.

Note the attribute async nay has an effect on inline scripts, for example:

<script async>foobar();</script>

When a script tag is requested to render the page is "locked" at that time until the script is fully downloaded and processed, then only from this point what comes after it will be loaded, however many things are unnecessary to wait for the script to load, then you can use:

<script src="..." async></script>

What will make the script to load parallel/simultaneously without locking the rendering, that is to say, you will not need to load the whole script so that the page can render itself Pagespeed Insights suggests you do this for a better "user experience" (UX), I answered other questions on the subject, see:

Support

In some older browsers that support the async use async=false on dynamically added elements did not work as expected

In accordance with kennel

  • Firefox 3.6+
  • Internet Explorer 10+
  • Chorme 8+
  • Safari in iOS 5.0+
  • Native Android browser 3+
  • Safari 5 on Mac

Multiple Javascripts with dependencies

Example script to load multiple . js that have dependencies on each other, ie one . js depends on whether the other is loaded, but still avoid rendering blocking:

<script>
//Esta função carrega os arquivos javascript
function loadJs(url, callback) {
    var js = document.createElement("script");

    //Verifica se o callback é uma função
    if (typeof callback === "function") {
        var isReady = false;

        //Executa se for carregado no onload ou readystatechange
        function ready() {
             if (isReady) return;

             //Bloqueia execução repetida do callback
             isReady = true;

             //Chama o callback
             callback();
        }

        js.onload = ready;

        /*Internet explorer (http://stackoverflow.com/q/17978255/1518921)*/
        js.onreadystatechange = function() {
            if (/^(complete|loaded)$/.test(js.readyState)) ready();
        }
    }

    js.async = true;
    js.src  = url;
    document.body.appendChild(js);
}

loadJs("js/jquery.min.js", function() {
    loadJs("js/bootstrap.js"); //Depende do jQuery
    loadJs("js/plugin.js"); //Depende do jQuery
});

//Não depende do jQuery
loadJs("js/outros-scripts.js");
</script>

1

The attribute "async" serves to make the loading of scripts happen without blocking the normal loading of other elements of the page. So it does not stop what it is "doing" to be able to load its script.

The best way to load scripts without the "async" attribute is at the bottom of the page, so it loads after all elements are loaded.

To fire the scripts you will have to "link" the functions to the elements you need, (As I do not know your page and the elements, I have no way to say the correct way to perform.)

1

make your script verify that the page is already loaded before registering the script for execution.

However, I advise you to use "onreadystatechange" instead of "onload".

var loadScript = function (script) {
  if (document.readyState == "loading")
  {
    document.addEventListener("readystatechange", function (event) {
      if (document.readyState == "interactive") {
        script();
      }
    });
  }
  else
  {
    script();
  }
}

loadScript(function () {
  console.log("Hello World!");
});

the possible values for the **document.readyState** sane.:

  • loading: Browser has not finished loading all elements DOM.
  • interactive: Browser has finished loading the elements DOM, but it is still loading the other elements (images, videos, etc).
  • complete: Browser has finished loading all page elements.

Now on to the attribute async tag script, he was added by HTML5, next to the attribute defer.

  • async: The scripts marked with async will run in parallel, ideal for scriptis not dependent on each other.
  • defer: The scripts marked with defer will wait for the page to finish loading the elements DOM for it to be carried out, that is to say, a behaviour similar to that of document.addEventListener("readystatechange", () if (document.readyState == "interactive")) { ... }) and similar to putting the script at the end of the body.

Remembering that these two attributes have no effect on scripts dynamically created.

  • Can you explain why you recommend readystatechange instead of onload? Is it a support issue? To be able to intercept a different moment in the shipment?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.