0

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.

RRR
  • 3,937
  • 13
  • 51
  • 75

2 Answers2

1

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]);
            }
    });
Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • that is exactly my question - how can I force the $.getScript to be performed before the for loop. – RRR Jun 10 '13 at 12:52
0

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

Exor
  • 402
  • 5
  • 8
  • which code does I have to put in the onload? the $.getscript...? – RRR Jun 10 '13 at 11:48
  • $(function(){ var Map = {}; $.getScript("cordova-2.6.0.js",function(){ Map['x'] = somthin } }); – Exor Jun 10 '13 at 11:49
  • $(document).ready(function() { // Handler for .ready() called. }); Which is equivalent to calling: $(function() { // Handler for .ready() called. }); – Exor Jun 10 '13 at 11:56