Is the "async" attribute used to execute dynamically loaded scripts? (AJAX) [closed]

1

I have a problem with content loaded in AJAX .

It is as follows : When I load scripts via ajax, I do not have " onload " or similar events to be able to trigger the loaded script. Does the async attribute on the script tag solve 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 have invested their time in answering. I tried to delete the question, but I could not.

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

    
asked by anonymous 10.06.2017 / 09:57

3 answers

5

No , the use of the async attribute on <script src="..."> elements is to avoid blocking-rendering .

On the use of Ajax I really do not think it takes so much work, you can just load the script dynamically with document.createElement , nor even need async , however it's good to use it, at the end of the answer you have an example of how to load dynamically.

  

Note that the attribute async does not has an effect on inline scripts, for example:

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

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

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

What will cause the script to load in parallel / concurrently without crashing rendering, ie you do not need to load the entire script so that the page can render, itself # suggests that you do this for a better "user experience" (UX), I've answered other questions about it, see:

Support

  

Some older browsers that support async use async=false in dynamically added elements did not work as expected

As caniuse

  • Firefox 3.6 +
  • Internet Explorer 10 +
  • Chorme 8 +
  • Safari in iOS 5.0 +
  • Android 3+ native browser
  • 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 the other being loaded, but still avoid rendering block:

<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>
    
10.06.2017 / 15:34
1

Make sure your script checks that the page is already loaded before registering the script to execute.

However, I advise you to use the onreadystatechange instead of the 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!");
});

Possible values for **document.readyState** are.:

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

Now for the async attribute of the script tag, it was added by HTML5 , next to the defer attribute.

  • async : script s marked with async will run in parallel, ideal for script s that has no dependency.
  • defer : The script s marked with defer will wait for the page to finish loading the DOM elements to execute, that is, a behavior similar to 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% s with dynamically created%.

    
10.06.2017 / 14:38
0

The "async" attribute serves to load scripts without blocking normal loading of other elements of the page. So he does not stop at what he's "doing" in order to load his script.

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

To launch 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 can not say the correct way to do it.)

    
10.06.2017 / 14:22