简体   繁体   中英

JQuery: Why does ajax request execute before code in beforeSend finishes executing?

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);
    }
});

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";
    }
});

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.

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, aso

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM