John Moore John Moore - 1 month ago 4x
Ajax Question

How to fetch some JSON files on page load? (Is synchronous inevitably bad)?

I have a web application whose entire functionality is dependent on 3 JSON files being fetched from the server and processed when the main page is loaded. At the moment, I use jQuery AJAX calls, with 'async:false', and it works fine. But everything I read is shouting at me that synchronous AJAX is evil and that I should refactor this to asynchronous behaviour. Of course I could do that, at the expense (as I see it) of making the code rather messier, in that the entire application would be loaded in the AJAX success function.

My question is whether I should really go ahead and refactor, given that this appears to me to be a possibly justified case for synchronous behaviour. Yes, the application will be unresponsive if there's a problem with the AJAX call, but it would also be unresponsive if there were a problem loading one of the key JS files, say, would it not? And given that the application is effectively unusable (can't do anything worthwhiile) until the JSON files are loaded anyway, does it matter?

Maybe I've missed a simple way of loading JSON files which doesn't involve the use of AJAX at all? That would be a cleaner solution, certainly.


If the files are located in your server, perhaps you can try this approach:

Define the JSON like this in a file:

data = '[
    {"name" : "Ashwin", "age" : "20"},
    {"name" : "Abhinandan", "age" : "20"}

Then you just include the json file in your HTML.

<script type="text/javascript" src="data.json"></script>
<script type="text/javascript" src="javascrip.js"></script>

Finally, just use the data as a variable:

var mydata = JSON.parse(data);

Disclaimer: I just found this 10 minutes ago here