Does deferred.resolve() wait until the line before it completes? My code works, but I can't tell if deferred.resolve() is actually happening after the image finishes loading or if it's executing after the request for the image is initiated but before it finishes loading.
test = function(deferred) {
$('<img src="https://upload.wikimedia.org/wikipedia/commons/7/72/%27Calypso%27_Panorama_of_Spirit%27s_View_from_%27Troy%27_%28Stereo%29.jpg">');
deferred.resolve();
};
$.when($.Deferred(test)).then(function() {
document.location = "https://stackoverflow.com/";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Or do I need to add a load handler to the image like so?
test = function(deferred) {
$('<img src="https://upload.wikimedia.org/wikipedia/commons/7/72/%27Calypso%27_Panorama_of_Spirit%27s_View_from_%27Troy%27_%28Stereo%29.jpg">').on("load", function() {
deferred.resolve();
});
};
$.when($.Deferred(test)).then(function() {
document.location = "https://stackoverflow.com/";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
The problem I've found with adding an .on("load", handler) is if the image fails to load for some reason, deferred.resolve() is never executed. I tested this with using a bad url.
I need to be able to guarantee that the page redirect happens after the image loads, but also that the image won't block the redirect from happening if there is an error loading the image.