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?
source share