I am currently developing a script that will fetch a specific resource r
from the server upon request using AJAX (asynchronously), and then execute a callback function f
with the returned resource.
To optimize performance, I want the script to not make another AJAX call if the requested resource is already being fetched. Instead, it should trigger the callback once the ongoing download of the resource is completed:
JavaScript
var nowLoading = {};
/**
* @param {String} r - The resource identifier
* @param {Object} f - Callback function with returned resource
*/
function Load(r, f)
{
if (nowLoading.hasOwnProperty(r))
{
// the requested resource is already loading, so wait for it to finish
nowLoading[r].OnReady = function () {
// ...
f(resource);
};
}
else
{
// initiate a new request
var xhr = XHRFactory.Spawn();
nowLoading[r] = xhr;
xhr.OnReady = function () {
// ...
f(resource);
};
xhr.open('GET', url);
xhr.send();
}
};
Is there any chance, however small, that the AJAX call completes between nowLoading.hasOwnProperty(r)
and nowLoading[r].OnReady = fn
statements?
Or have I misunderstood JavaScript in this context, and can OnReady
only occur after all sequential statements are executed?
If the former is true, it could mean that the callback attached to a property of nowLoading
may never be called, as OnReady
occurred before it was attached.
NOTE: OnReady
is a custom case of XHR.onreadystatechange
. Additionally, please note that for simplicity, OnReady
does not clear the previous handler, but simply adds a new one.