Reputation: 57
This is my code. Basically I have a Reload.gif that I want to start playing on my page before I send an ajax request to reload my data. However what ends up happening is it will only start playing after my success function is called. This is what the timeline looks like:
0:00 seconds: 1 logged to console
0:00 seconds: 2 logged to console
0:10 seconds: 3 logged to console
0:10 seconds: GIF starts playing.
This doesn't make sense, is setting the src of an img async or something? Image code:
<img id="reloadIcon" src="/img/Reload.png" style="width: 25px; height: 25px"/>
jQuery.ajax({
url: url,
type: 'GET',
timeout: 20000,
beforeSend: function() {
console.log(1);
document.getElementById('reloadIcon').src = "/img/Reload.gif";
console.log(2);
},
success: function (result) {
console.log(3);
}
});
Upvotes: 2
Views: 2557
Reputation: 138
If you change the src attribute, the browser must complete a bunch of things like look for the image in its cache, probably re-request the image, parse, a.s.o.
Second, your JS code shares one thread with a lot of other things. Browsers tend to internally cache CSS assignments and execute the following JS code first, as long as the right-then missing, cached changes will not affect the functionality of your code. If you want to force assignment in this case, read the specific CSS property, and the browser will assign the changes before. I tend to state (without having tested), there's such behaviour on attributes as well.
Best practice in this case is the post from guest271314, hiding and showing the outer container is much faster and reliable.
Upvotes: 0
Reputation: 9
Fetching the image by changing "src" is asynchronous, I think you can just set the src when the page is load but make the image element invisible. And set the image visible when ajax begin.
Upvotes: 0
Reputation: 1
Load the image before $.ajax()
call. Toggle the CSS display
property of the <img>
element at beforeSend
function, instead of changing the .src
of the <img>
element.
jQuery.ajax({
url: url,
type: 'GET',
timeout: 20000,
beforeSend: function() {
console.log(1);
document.getElementById('reloadIcon').style.display = "block";
console.log(2);
},
success: function (result) {
document.getElementById('reloadIcon').style.display = "none";
console.log(3);
}
, error: function() {
document.getElementById('reloadIcon').style.display = "none";
}
});
Upvotes: 3