Access to global variables with script loader injected scripts

1.3k views Asked by At

I'm trying to wrap my head around a particular subtlety of using asynchronous script loaders (head.js, yepnope, etc.). I have a page setup like so:

<body>
    <script type="text/javascript" scr="yepnope.js"></script>
    <script type="text/javascript">
        var important_stuff = { "key" : "value", "another key" : "value"};
        yepnope([
            { load: "some/script.js" },
            { load: "another/script.js" }
        ]);
    </script>
</body>

When I inspect the resulting HTML for this page in Firebug I notice that yepnope has injected the <script> tags for my two scripts above its own tag. My question is: will the 2 scripts loaded with yepnope have access to the important_stuff global variable even though they are injected above where it is defined? Thanks.

1

There are 1 answers

1
jfriend00 On BEST ANSWER

All global variables are global. Once it's loaded and defined, it is available to everything that exists at the time or to all things that get loaded later. So, it only matters what the load order is, not where the script tags are inserted.

if the two dynamically loaded scripts are sequentially loaded after your globals are defined, then they will have access to the globals regardless of the order of the script tags.