Reputation: 6832
I'm fetching data (summarizing timeframes) for my dashboard asynchronously by using $.GET(). The script is simple, I'm waiting that the page (fonts, icons..) is completely rendered by using $(window).load(function () {}
.
Then I'm using a document.querySelectorAll('[data-id]');
to search the related ids and start a query in a for loop.
// some date ranges I'm using for the request
var request = [
[moment(), moment(), 'today'],
( ... )
[moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year').endOf('year'), 'last-year']
];
// find all data-id elements
var t = document.querySelectorAll('[data-id]');
for (var i = 0; i < t.length; i++) {
// extract the id
var mid = t[i].getAttribute('data-id');
// iterate the request array
for (var j = 0; j < request.length; j++) {
requestData(mid, request[j]);
}
}
function requestData(id, time) {
$.ajax({
url: "/api/v1/data/point/" + id,
type: 'GET',
data: {
from: time[0].format('YYYY-MM-DD'),
to: time[1].format('YYYY-MM-DD'),
sum: true
},
dataType: 'json',
success: function (response) {
// find elements by id stuff and replace the innerHTML with the response value (it is just to long to display here, but nothing special).
}
});
}
Q While the page is doing ~ 5-12 GET requests, the page is completely blocked and I can not load another page by clicking on a link. So whats basically wrong here? Is the behavior maybe also referable to the power of the web server that those 12 GET requests cause heavy load? I've also noticed that if I'm using jquerys $(document).ready function, that the icons are rendered after $.Ajax finishes - this results in squares instead of icons.
Edit: I thought that maybe the mysql calls by the API are blocking the server?
Edit2: async is true by default (http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings)
Upvotes: 3
Views: 1075
Reputation:
You can add async: false in AJAX call.
function requestData(id, time) {
$.ajax({
url: "/api/v1/data/point/" + id,
type: 'GET',
async: false,
data: {
from: time[0].format('YYYY-MM-DD'),
to: time[1].format('YYYY-MM-DD'),
sum: true
},
dataType: 'json',
success: function (response) {
// find elements by id stuff and replace the innerHTML with the response value (it is just to long to display here, but nothing special).
}
});
}
And if thats not work then replace it by true.
Upvotes: 1
Reputation: 561
Below are my ideas on how you can improve the state:
Upvotes: 0