RRR
RRR

Reputation: 4175

JavaScript - loading scripts order

I am developing an HTML+JavaScript application for Android OS. In the HTML page I am loading another JS file which has this code:

var Map = {};
$.getScript("cordova-2.6.0.js",function(){
Map['x'] = somthin
}

At the HTML page I am looping through the map. The problem is that, at the first time my application is loading, everything works well. But when I am openning other appliaction or just going back and then I am resuming my application the length of the map is equal to zero. (I think it relates to the order that the HTML page loads its dependencies, but I dont know how to solve this problem....)
Any suggestions? Thanks!

EDIT
My JS code in My JSFile.js:

var Map = {};
   $.getScript("cordova-2.6.0.js",function(){
        Map['X'] = 'hi';
  });

My JS code in the HTML page:

<head>
<script src="JSFile.js"></script>
</head>
<body>



$(document).ready(function(){

        for(var i in Map)
        {
            alert(Map[i]);
        }
});
</body>

The actual result is that in the first time the appliaction is loading, everything is working well - I am geting an alert "hi". But when the application is resuming - I am getting nothing.

Upvotes: 0

Views: 134

Answers (2)

Khanh TO
Khanh TO

Reputation: 48972

Put the code in the JSFile.js to the $(document).ready function like this:

var Map = {};
$(document).ready(function(){
   $.getScript("cordova-2.6.0.js",function(){
        Map['X'] = 'hi';
        for(var i in Map)
        {
            alert(Map[i]);
        }
  });
});

Remember that $.getScript is asyn, so if you call it like this, it will not work:

$(document).ready(function(){
    var Map = {};
       $.getScript("cordova-2.6.0.js",function(){
            Map['X'] = 'hi';
      });
    //Will not work because the response may not arrive yet
    for(var i in Map)
            {
                alert(Map[i]);
            }
    });

Upvotes: 1

Exor
Exor

Reputation: 402

Add that code in the onload event of the page.So that this code will be called when ever that page is going through a load event

Upvotes: 0

Related Questions