jQuery has deprecated synchronous XMLHTTPRequest
Asked Answered
R

7

129

Like many others, my website is using jQuery. When I open the developer tools, I see a warning that says that XMLHTTPRequest is

deprecated because of its detrimental effects to the end user's experience.

I went on and read part of the documentation, but it was fairly technical. Can someone explain the consequences of shifting from XMLHTTPRequest to WHATWG in simple terms? It says it happened in 2012.

Also, the documentation says that Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform, when that happens, if a user agent had them in a service, do they need to modify their existing code?

Recalescence answered 2/1, 2015 at 0:53 Comment(10)
You must be talking about synchronous XMLHTTPRequests, not asynchronous ones, correct? Synchronous requests are horrible for the end user experience (they lock up the browser during the request) and should generally not be used.Casement
provide some code that triggers thisAlpheus
I'm not writing any service code at this moment, my concern is: I want to learn to write code that doesn't require avoidable maintenance over time. I know I could work with ajax, but I haven't grasped the concept just yet. I used the jquery example for that reason. @AlpheusRecalescence
Is this the full text in question? Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.Milewski
Specifications for different parts of browser APIs are sometimes moved around between different organisations -- this does not usually change anything for developers themselves.Milewski
jQuery only gives that warning for synchronous requests, doesn't it? Are you deliberately making a synchronous request? If so, the solution is to structure your code to work with asynchronous requests, which you should do anyway because they're much nicer from the user's point of view.Ottavia
I've seen that flag not only in my website, I've seen it some others, e.g. Youtube, as well. Regarding specifications, with what specification should my code be in compliance, W3C's or WHATWG's? , reference I don't want to ask in the main thread for it would be flagged as a matter of opinion I guess. @Qantas94HeavyRecalescence
It is not jquery, it's chrome - src.chromium.org/viewvc/blink?view=revision&revision=184788Imperforate
please to edit the text of the flag to what Qantas pointed out. XMLHTTPRequest is not the subject of the issue, it is the synchrounous one on the main THREADAbolition
Possible duplicate of Javascript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."Michalemichalski
O
146

To avoid this warning, do not use:

async: false

in any of your $.ajax() calls. This is the only feature of XMLHttpRequest that's deprecated.

The default is async: true, so if you never use this option at all, your code should be safe if the feature is ever really removed.

However, it probably won't be -- it may be removed from the standards, but I'll bet browsers will continue to support it for many years. So if you really need synchronous AJAX for some reason, you can use async: false and just ignore the warnings. But there are good reasons why synchronous AJAX is considered poor style, so you should probably try to find a way to avoid it. And the people who wrote Flash applications probably never thought it would go away, either, but it's in the process of being phased out now.

Notice that the Fetch API that's replacing XMLHttpRequest does not even offer a synchronous option.

Ouellette answered 2/1, 2015 at 1:30 Comment(29)
This is jQuery's warning then. I can ignore it? I don't use synchronous calls to the server. The perfectionist side of me doesn't like having warnings at all.Hanging
@Hanging I think the warning is coming from the browser, not jQuery. It will happen whenever you try to use synchronous AJAX. If you use jQuery, that will only happen if you specify that option to $.ajax.Ouellette
I am working with jquery-2.1.4.min.js and I have the same warning on Firefox, Chrome and Opera, and I am not using $.ajax(). When I do click in that warning it opens the jquery-2.1.4.min.js file of course.Forearm
You must be using some other library that uses $.ajax.Ouellette
I am using jquery.i18n.properties.js but there is no an explicit call by my side to $.ajax. Perhaps internally, but not sure.Forearm
Something must be calling $.ajax with that option. Or maybe there's a call to $.ajaxSetup that sets it as the default. But the warning message doesn't happen for no reason.Ouellette
That plugin loads resource bundles from .properties files. It's probably using synchronous AJAX to do it, causing this warning.Ouellette
Look on line 74 of github.com/jquery-i18n-properties/jquery-i18n-properties/blob/…Ouellette
Good catch @Ouellette I am going to report it on its page how an issue. Thanks!Forearm
Mine must have something to do with $('.modal').on('shown.bs.modal', function (e) { $(remote_target).load(remote); });You
@ManuelJordan I had the same warning, you can call $.i18n.properties with async: true parameter $.i18n.properties({ async: true, name: 'messages', ....... }); (maybe you have solved, but for the others... )Fighterbomber
@Ouellette i ahve tried with giving async value as true, but still it is showing me the same error is there any other thing which i have missedTourist
@Tourist Are you sure the warning is coming from your AJAX call, not a third-party library you're using?Ouellette
@ManuelJordan setting async: true in i18n can cause a delay in showing the strings displayed in your page on slow connection. Showin instead the string codeMelitamelitopol
@TSion.D.P If the connection is slow, you'll have a delay either way. Synchronous AJAX will block the browser while waiting for the request to complete.Ouellette
I need to using that feature for onetime token, does it have any other solution?Remedial
@Remedial You should write proper asynchronous code that uses the token in a callback. See #14220821Ouellette
This warning still appears even when the async option is not explicitly used because jQuery still sends a boolean representative to XMLHttpRequest.open(), defaulted to true. I've come to the conclusion that this is not an issue as I never explicitly set async, and the notice will stop occurring once the async option is removed from jQuery.Justness
@AufgeschissenerKunde The issue isn't whether the async option is used explicitly or not. The warning only appears when you request synchronous AJAX. I never see the warning from my $.ajax calls.Ouellette
This totally avoids an obvious question of what if a person wants synchronousAraliaceous
@Ouellette yeah async :true is fine and this doesn't answer what if he wants syncAraliaceous
@Araliaceous Then they're in danger of their code not working if and when synchronous AJAX is actually removed from browsers. The deprecation message is a warning that this might happen in the future.Ouellette
If you actually want it, code it and ignore the messages. The user never sees them unless they open the console.Ouellette
@Araliaceous I've updated my answer to address your question some more.Ouellette
I am seeing this when doing $.get(), should not that be async by default?Thumbscrew
@Thumbscrew Yes, unless you've used $.ajaxSetup() to change the default.Ouellette
@Ouellette No, I did not use $.ajaxSetup() at all, but the warning is there.Thumbscrew
@Thumbscrew Something in your code must be overriding the jQuery default. I can't think of any reason.Ouellette
Anybody else: turn on LogXMLHttpRequests in Console. It showed me that inside the page that I was correclty loading with an async get there was a <script src="[...]"> tag in the body, which made a synchronous request causing the error above.Thumbscrew
R
63

The accepted answer is correct, but I found another cause if you're developing under ASP.NET with Visual Studio 2013 or higher and are sure you didn't make any synchronous ajax requests or define any scripts in the wrong place.

The solution is to disable the "Browser Link" feature by unchecking "Enable Browser Link" in the VS toolbar dropdown indicated by the little refresh icon pointing clockwise. As soon as you do this and reload the page, the warnings should stop!

Disable Browser Link

This should only happen while debugging locally, but it's still nice to know the cause of the warnings.

Resonate answered 16/9, 2015 at 17:46 Comment(9)
One can disable in web.config by adding <add key="vs:EnableBrowserLink" value="false" /> inside <appSettings> as described here: poconosystems.com/software-development/….Icterus
I think this is a bad suggestion just to get ride of warning messages in the console. Disable browserlink and get rid of the productivity enhancements that browserlink adds just so you won't see a warning message in the browser console? Better to file a bug with microsoft and it gets fixed.Blocked
@Blocked Thanks for your opinion; you can feel free to file a bug with Microsoft. I wasn't saying you should disable Browser Link. My answer is accurate as to the cause of this warning in some cases and it's useful to rule out something in your own code. I personally felt better once I realized it wasn't something I did wrong and thought others might find it helpful as well.Resonate
This fixed more than just the ajax warning. I got all kinds of browser link mess in the javascript console using asp core.Crosscurrent
Would anyone know what is browser link and why does it end end up giving such a warning?Aili
Browser link is useful because it inserts a script into your page during debugging, which allows communication between the page with Visual Studio, using Javascript and SignalR. So if you change a certain HTML file, content will be updated in the page automatically. Changing a CSS file will also make style changes immediately visible in the browser without the need to refresh it. So if the only thing that bothers you is the warning, you don't need to disable it.Denims
Did anyone ever file a bug report for this at MS? I looked at developercommunity.visualstudio.com but maybe is one somewhere else? Otherwise I would create one.Restivo
Browser should provide backward compatibility to synchronous call. Because, there are lots of code which used synchronous call. I even notice that jqgrid4.1 is still using synchronous method. It is really horrible and discouraging if they really remove it from browser.Chimpanzee
Thank you so much @Sam. I fought with the Synchronous XMLHttpRequest issue for days until I found your solution. I disabled the browser link and the messages are gone. Now I just have to figure out why I can't get the .done(function()...) part to work. Thank you again.Kaden
P
17

This happened to me by having a link to external js outside the head just before the end of the body section. You know, one of these:

<script src="http://somesite.net/js/somefile.js">

It did not have anything to do with JQuery.

You would probably see the same doing something like this:

var script = $("<script></script>");
script.attr("src", basepath + "someotherfile.js");
$(document.body).append(script);

But I haven't tested that idea.

Persis answered 21/5, 2015 at 17:51 Comment(1)
The warning went away for me when I removed a line like this, which I wasn't using anyway: @Html.Script("~/scripts/apps/appname.js")Official
R
11

It was mentioned as a comment by @henri-chan, but I think it deserves some more attention:

When you update the content of an element with new html using jQuery/javascript, and this new html contains <script> tags, those are executed synchronously and thus triggering this error. Same goes for stylesheets.

You know this is happening when you see (multiple) scripts or stylesheets being loaded as XHR in the console window. (firefox).

Remainderman answered 2/10, 2018 at 9:11 Comment(0)
A
2

No one of the previous answers (which all are correct) was suited to my situation: I don't use the async parameter in jQuery.ajax() and I don't include a script tag as part of the content that was being returned like:

<div> 
     SOME CONTENT HERE
</div>
<script src="/scripts/script.js"></script> 

My situation is that I am calling two AJAX requests consecutively with the aim to update two divs at the same time:

function f1() {
     $.ajax(...); // XMLHTTP request to url_1 and append result to div_1
}

function f2() {
     $.ajax(...); // XMLHTTP request to url_2 and append result to div_2
}

function anchor_f1(){
$('a.anchor1').click(function(){
     f1();
})
}

function anchor_f2(){
$('a.anchor2').click(function(){
     f2();
});
}

// the listener of anchor 3 the source of problem
function anchor_problem(){
$('a.anchor3').click(function(){
     f1();
     f2();
});
}

anchor_f1();
anchor_f2();
anchor_problem();

When I click on a.anchor3, it raises the warning flag.I resolved the issue by replacing f2 invoking by click() function:

function anchor_problem(){
$('a.anchor_problem').click(function(){
     f1();
     $('a.anchor_f2').click();
});
}
Abolition answered 24/10, 2015 at 17:38 Comment(3)
Scripts are not executed if you directly insert them into the DOM via innerHTML. So when you call .html(), jQuery fetches and executes any scripts included in the html response synchronously.Tentative
@HenryChan, I tried to understand you but to no avail. Could you please explain to me in simpler words. I don't insert scripts into the DOM, I insert only HTML and still this solution is the only working solution for me. Thanks in advanceAbolition
@whitelettersinblankpapers I think he means: inside your ajax callback, if the contents that you append to your "div"s contain script tags, then these will be called synchronously.Dhu
A
0

My workabout: I use asynchronous requests dumping the code to a buffer. I have a loop checking the buffer every second. When the dump has arrived to the buffer I execute the code. I also use a timeout. For the end user the page works as if synchronous requests would be used.

Allegorist answered 10/4, 2015 at 7:48 Comment(2)
do you have a little bit code for me to know how to achieve this?Alforja
@runback, can't the done() promise callback be used ? $.ajax({ url : "example.com", async : true /* default is true */ }).done(function(response){ // Process the dump }) Hope I have not mis-read anything.Di
A
0

I investigated this error a little further and came to the conclusion that the error comes from here:

    jQuery.ajaxTransport( function( options ) {
    ...

            xhr.open(
                options.type,
                options.url, 
                options.async, // This one
                options.username,
                options.password
            );
    ...

If you set it to true the error dissappears even if you set back to options.async. So maybe a good solve to this problem is using a downloaded version of the jquery file and modify this line (in the 3.2.1 file is on 9400~)

August answered 22/9, 2023 at 17:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.