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 have found two different ways to implement it. First, using the .holdReady()
function in jQuery:
The
$.holdReady()
method allows the caller to delay jQuery'sready
event. This advanced feature would typically be used [...] to load [...] before allowing the ready event to occur
So in my case, the code should look like this:
<html>
...
<script type="text/javascript">
var json = {};
$.holdReady(true);
$.getJSON(url, '', function(data) {
json = data;
$.holdReady(false);
});
$(whatever);
</script>
...
</html>
Another option, using custom events (thanks to freedomn-m 's suggestion in the comments), would be something like this:
<html>
...
<script type="text/javascript">
var json = {};
// Request the JSON file
$.getJSON(url, '', function(data) {
// When it's retrieved, store the data in the `json` variable
json = data;
// And when the DOM is ready...
$(function() {
// ...trigger the custom `jsonReady` event
$(document).trigger('jsonReady');
});
});
</script>
...
</html>
The only change required is to replace all the $(whatever);
for $(document).on('jsonReady', whatever);
.
There is a simpler way of doing things ;)
let json = {} $(document).ready(() => { function whatever() { // do some stuff console.log('run the program'); } $.getJSON('https://jsonplaceholder.typicode.com/users', (data) => { json = data; console.log(json); }) .then(() => whatever()); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>Some paragraph</p>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.