Reputation: 1314
I am looking for some more information on how browsers execute async style scripts with regards to the rest of the page.
I have a JS script that follows the async loading pattern like so:
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 downloads. So far so good. Now lets say later on I declare some variable:
var x = "something";
My question is, will this variable be available to the script I loaded previously? If I do a
alert(x);
in the script loaded above, it seems to work but I'm not sure it will always be the case. Also what about DOM elements. If there is some div later on in the page:
<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 it would be visible to the async script or not.
So my question can be basically narrowed down to, is it safe to access items from a asynchronously loaded script without checking for some DOM loaded event?
Upvotes: 4
Views: 2482
Reputation: 75317
By adding a <script>
with async
set to true and then declaring a variable in a <script>
lower down the pecking order, it's a race condition whether the variable is available in the first.
If the first <script>
is cached, or if the execution of the second <script>
is delayed (i.e. an element inbetween the first/ second is synchronous and slow to load) you will end up with the variable being undefined.
You can guarantee that a <script>
will execute no earlier than it's position in the DOM. If the <div>
is positioned before the <script>
, it will always be available. Otherwise pull straws.
In both of these situations you can wrap JavaScript code contained within the scripts in event handlers which are listening for an event such as window.onload
or DOMContentLoaded
event to delay the execution until those events have fired (and all <scripts>
will be present and correct).
Upvotes: 1