JQuery click function does not work intermittently

Wow, this is tearing my hair apart.

I track links in jQuery.

$(".hdr a[id]").mousedown(function(e){
    var h = this;
    var url = "/g/click/" + this.id;
    $.get(url);
  });

It seems like sometimes the browser beats the ajax call. A new page is loaded before the click tracker starts. (This is not a slow response time, the request did not even hit apache). It is intermittent and not easily reproducible, but it usually appears after the user does a lot on the site.

I used preventDefault in an earlier iteration of this, but in the end it breaks cmd-click and doesn't track right clicks.

Is there any way to guarantee that this will work?

Thank you for your help.

+3
source share
2 answers

, , : $. post() ? , :

$.ajaxSetup({async: false});

, , .

+2

, . , , URL- . URL- .ajax cache: false.

asynch: false, ui, , .

$(".hdr a[id]").mousedown(function(e){
    var url = "/g/click/" + this.id;
    $.ajax({
         url: url,
         cache: false,
         success: function(data){
                 //do something with the response
                 }
         });
});

N.B , setTimeout script. -, mousedown . xhr-, , mousedowns .

+1

Source: https://habr.com/ru/post/1713064/


All Articles