Asynchronous Javascript loading and execution order

I am looking for more information on how browsers execute asynchronous style scripts with respect to the rest of the page.

I have a JS script that follows the async boot pattern as follows:

var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = 'http://yourdomain.com/script.js'; var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); 

I understand that this is a non-blocking download, and the page will continue to load while this download is loading. So far, so good. Now let's say later, I declare some variable:

 var x = "something"; 

My question is: will this variable be available for a previously loaded script? If i do

 alert(x); 

in the script downloaded above, it seems to work, but I'm not sure if this will always be the case. As for the DOM elements. If the page has another div:

 <div id="myDiv"></div> 

and in my script i do

 var div = document.getElementById("myDiv"); 

Will this work correctly? In my testing, these things seem to work, but I'm not sure if there was much more page content that would be visible to the async script or not.

So my question can be mostly narrowed down, is it safe to access elements from an asynchronously loaded script without checking for any loaded DOM event?

+4
source share
1 answer
  • Adding <script> with async to true and then declaring the variable in <script> lower in the hierarchy is a race condition to see if the variable is available in the first.

    If the first <script> cached, or if the execution of the second <script> delayed (i.e. the element between the first and second synchronous and slow to load), you will get an undefined variable.

  • You can guarantee that <script> will not be executed before the position in the DOM. If the <div> positioned before the <script> , it will always be available. Otherwise, pull out the straw.

In both of these situations, you can wrap JavaScript code contained in scripts in event handlers that listen for an event, such as a window.onload event or DOMContentLoaded , to delay execution until these events are fired (and all <scripts> will be be present and corrected).

+1
source

Source: https://habr.com/ru/post/1396699/


All Articles