Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registering an async javascript, declarative (static) vs dynamic

Is there any difference in declaring my async javascript statically vs dynamically?

static

<html>
<head>
  ...
</head>
<body>
  ...
  <div id='my-script-needs-me'></div>
  <script type="text/javascript" src="https://foo.bar/myscript.js" async>
  </script>
  ...
</body>
</html>

dynamic

<html>
<head>
  ...
</head>
<body>
  ...
  <div id='my-script-needs-me'></div>
  <script type="text/javascript">
      var myScript = document.createElement("script");
      myScript.src = 'https://foo.bar/myscript.js';
      myScript.async = !0;
      myScript.type = 'text/javascript';
      document.getElementsByTagName('head')[0].appendChild(myScript);
  </script>
  ...
</body>
</html>

I noticed that declaring a script statically let a browser detect it earlier and preload (chrome + firefox).

My goal is to load a javascript in async way in order not to block HTML rendering and other scripts execution. Sametime, I want it to be executed as soon as it's downloaded, having in mind that it requires one element to be in the DOM already. Once downloaded the script is executed and it accesses the my-script-needs-me div. One limitation, I cannot change the script itself.

like image 347
Alexey Strakh Avatar asked Mar 17 '17 20:03

Alexey Strakh


People also ask

What is the difference between static and dynamic variable types?

That’s why it is possible to assign, for example, string “abc” to the variable a, and later on re-assign another value, for example, Number. It means that type of the variable is set dynamically during code execution and moreover this type can change during code execution. That is a difference between static and dynamic type languages.

What is dynamic type in JavaScript?

Again javascript is dynamic type language and it means that you are free to re-assign the value of any type to an existing variable that was defined of course using either let or var. Let’s now look at the above code that is totally valid in javascript.

What is the difference between synchronous and asynchronous in JavaScript?

Synchronous means executing statements one after the other which implies the next statement will get executed only after the previous statement is executed completely. Whereas in Asynchronous calls the next statement gets executed without even waiting for the previous one’s execution. JavaScript is a Synchronous language.

How does JavaScript stack work?

When the JavaScript engine invokes a function, it adds it to the stack, and the execution starts. If the currently executed function calls another function, the engine adds the second function to the stack and starts executing it. Once it finishes executing the second function, the engine takes it out from the stack.


3 Answers

supports async parameters allowing to make this call asynchronous.

The second way you described allows you to have the url as a parameter and bind it. It allows too the use of a callback to do some stuff when your script is loaded.

let scriptElement = document.createElement('script');
let url = `https://maps.googleapis.com/maps/api/js?key=${apiKey}`;//&libraries=geometry
  scriptElement.src = url;
  //Chargement de l'API Google
  scriptElement.onload = () => {
    //API chargée, on peut lancer l'initialisation du composant
    this._initializeMap();
  };

I used this to load Google Maps API, it's not directly in the HTML, so i can modify the URL when my page loads. And when the API is loaded, I an launch treatments that need this API.

like image 158
Guillaume Grimbert Avatar answered Oct 11 '22 00:10

Guillaume Grimbert


you can use defer for that instead of async.

your script will execute right after html be parsed.

like image 35
Mike Datsko Avatar answered Oct 11 '22 01:10

Mike Datsko


Static

<html>
<head>
  ...
</head>
<body>
  ...
  <div id='my-script-needs-me'></div>
  <script type="text/javascript" src="https://foo.bar/myscript.js" async>
  </script>
  ...
</body>
</html>

As you know, HTML is parsed top-bottom. So, if it placed within body tag, then as soon as parsed, if it is an IIFE or the file myscript.js contains a function call, it will execute immediately.

So, inside, body, put it the script at the bottom will help you to execute it after the div has loaded.

But we can't ensure because of caching.

If the browser cache the script and if it is an IIFE or contains a function call, we can't predict the behaviour.

Dynamic

In dynamic also, it depends on the order.

<html>
<head>
  ...
</head>
<body>
  ...
  <div id='my-script-needs-me'></div>
  <script type="text/javascript">
      var myScript = document.createElement("script");
      myScript.src = 'https://foo.bar/myscript.js';
      myScript.async = !0;
      myScript.type = 'text/javascript';
      document.getElementsByTagName('head')[0].appendChild(myScript);
  </script>
  ...
</body>
</html>

In both cases, it will render after HTML contents.

The best way to ensure it loads only after all contents are loaded is

Giving an eventListener on Window.

Check the code below

<html>
<head>
  ...
</head>
<body>
  ...
  <div id='my-script-needs-me'></div>
  <script type="text/javascript">
     function load(){
        var myScript = document.createElement("script");
        myScript.src = 'https://foo.bar/myscript.js';
        myScript.async = !0;
        myScript.type = 'text/javascript';
        document.getElementsByTagName('head')[0].appendChild(myScript);
     }
     window.addEventListener("DOMContentLoaded",load);
  </script>
  ...
</body>
</html>

Check this line window.addEventListener("DOMContentLoaded",load);.

The DOMContentLoaded is similar to jQuery's $(document).ready(). It will trigger the callback function when the HTML is properly loaded. So, you don't have to check for the existence of the HTML Element.

like image 1
Sagar V Avatar answered Oct 11 '22 00:10

Sagar V