Reputation: 1011
I have a search engine, and at the bottom of the results, it has recommended similar words. However the similar words function takes a while to load. For user experience I wanted to first show the search results, and then load the similar words, once the search results were shown, or asynchronous as to not slow down the page load.
My two ideas were, 1. to call the similar words function once the container for it has been loaded (the container is below the search results). For this I was using:
$('#search_similar_cont').ready(function(){
// load similar words function through ajax
});
My other idea was to load it once the search results had finish loading,
$('#search_results').load(function(){ // load similar words function through ajax });
However, none actually worked, I also tried using on(). Therefor, I am not sure how to create the event to load content asynchronous on the site really. Also I am not even sure if this is the best approach to achieve what I am after.
What is the best way of loading a function (that is quite slow), without slowing down the main function of the page?
Upvotes: 0
Views: 74
Reputation: 216
You may want to go with promises:
You can call a Promise-function and add a .then()
function. Everything inside your .then()
function is executed after the promise has been resolved or rejected.
You can even chain promises one after another to create an asynchronous flow.
If you make your AJAX call within a function like this:
makeAjaxCall(method, url, payload, username, password) {
return $.ajax({
type: method,
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
},
data: JSON.stringify(payload),
error: function(data, statusText, xhr) {
console.log(data, statusText, xhr.status)
},
success: function(data, statusText, xhr) {
console.log(data, statusText, xhr.status);
}
});
}
You can then use the .then()
keyword like so:
makeAjaxCall().then(function(data, statusText, xhr){
do something after your ajax call is resolved..
},
function(data, statusText, xhr){
do something if the promise was rejected..
});
This works even without instanciating a Promise-object.
Read more about the JS promise object here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Upvotes: 1