I have a web application built with jQuery, and I need to load some JSON data before anything else is done. Currently, I'm doing it like this:
<html>
...
<script type="text/javascript">
// Load the data (directly injected into the HTML)
var json = { ... };
// Once the full DOM is loaded, do whatever I need
$(whatever);
function whatever() { ... }
</script>
...
</html>
It works, but it's extremely ugly. I'd rather load the actual JSON file, for example using jQuery's getJSON with a callback function. But calling AJAX functions in a synchronous way isn't allowed anymore (at least with jQuery). So... how do I make sure that my whatever method isn't called until that callback has finished?
Just calling $(whatever) from my callback function is not an option, because I actually have many of those $() distributed across the different pages of the application.
I actually have many of those $() distributed across the different pages of the application.stop you from using the callback? You could in each callback test if all the files you needed had loaded.var json = { ... };version, if possible - one less network request means slightly less time for the site's scripts to activate. If it's injected with PHP, for example, and you don't likevar json = <?php echo ..., you can put the JSON into ascripttag with a custom type instead and then parse itstextContent. Also note that there's no such thing as a JSON object - JSON is a string notation. A string can be JSON, but an object never is, so you might call the variable something likedatarather thanjson$.getJSON(url).done(function(json) { whatever(json); });- or are you saying you load the json all over the place? Or that all your doc.ready's rely on that json being preloaded? If so, instead of using a doc.ready, use listen for a custom event and raise the event on the $.getJSON handler. Or replicate the doc ready and call it when json loaded.jsonvariable, I just named that for the example, it's actually calleddatain my code :)