ChatGPT解决这个技术问题 Extra ChatGPT

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

I have been adding logs to the console to check the status of different variables without using the Firefox debugger.

However, in many places in which I add a console.log in my main.js file, I receive the following error instead of my lovely little handwritten messages to myself:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help http://xhr.spec.whatwg.org/

What alternatives to or wrappers for console.log can I add to my code use that will not cause this error?

Am I "doing it wrong"?

I don't see how a console.log() call would cause an ajax call, unless there's some kind of remote logging plugin enabled or whatever.
I'm not sure it's making an ajax call. Would it help if I included a screenshot?
xmlhttprequest is an ajax request, basically.
<script>$.ajaxPrefilter(function( options, originalOptions, jqXHR ) { options.async = true; });</script> this will removes the warning. You can see here for same issue.
I just used get instead of post, it helped. jQuery.

J
Joel Davis

This happened to me when I was being lazy and included a script tag as part of the content that was being returned. As such:

Partial HTML Content:

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

It appears, at least in my case, that if you return HTML content like that via xhr, you will cause jQuery to make a call to get that script. That call happens with an async flag false since it assumes you need the script to continue loading.

In situations like this one you'd be better served by looking into a binding framework of some kind and just returning a JSON object, or depending on your backend and templating you could change how you load your scripts.

You could also use jQuery's getScript() to grab relevant scripts. Here is a fiddle, It's just a straight copy of the jQuery example, but I'm not seeing any warnings thrown when scripts are loaded that way.

Example

<script>
var url = "/scripts/script.js";
$.getScript(url);
</script>

http://jsfiddle.net/49tkL0qd/


the error is because the OP is using somewhere an synchronous XMLHttpRequests, I don't think due jquery since doesn't seems that he use it... however this is happening to me when I try to load a <script> as you said in an callback of an ajax asynchronous call. My ajax call is asynchronous however in the callback I make $('#object').html(data) where data is a piece of html with <script> and when this line is executed the error appears in the js console. +1!!! thanks :).
For this project, I did, in fact, use JQuery.
@37coins, if this was the answer; mark it as so.. and replace javascript tag with jQuery.
This was my problem, and most likely the OP's problem too - OP please consider marking this as the answer. The higher voted answer here currently does nothing to help people with this problem, so accepting this answer would help others immensely.
just FYI jQuery getScript breaks caching. I think .ajax will do same and allow for caching
P
PedanticDan

The warning message MAY BE due to an XMLHttpRequest request within the main thread with the async flag set to false.

https://xhr.spec.whatwg.org/#synchronous-flag:

Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user's experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when the JavaScript global environment is a document environment. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an InvalidAccessError exception when it occurs.

The future direction is to only allow XMLHttpRequests in worker threads. The message is intended to be a warning to that effect.


no, the message warning is PRESUMABLY due to an XMLHttpRequest request within the main thread with the async flag set to false. This could very well be a bug in Firefox (but it's likely a jQuery feature/implementation); either way, how would describing part of the spec be considered an answer to a question that claims console.log is sending these warnings?
@Brett - the last two sentences of my answer explain why I included the part of the spec I did. I will edit my answer to be more precise.
with all that said, Everything you've stated in this answer is correct information; furthermore it's likely relevant to the likely problem; that is, the raising of this warning affects the behavior and/or stability of the debugger. Thus, the workaround may very well be to keep the warning from raising by correcting the cause of it.
They should add an about:flag to enable it for local debugging. Sync XHR can be very useful for tooling/debug frameworks running localhost.
H
Hakan Fıstık

I was also facing same issue but able to fix it by putting async: true. I know it is by default true but it works when I write it explicitly

$.ajax({
   async: true,   // this will solve the problem
   type: "POST",
   url: "/Page/Method",
   contentType: "application/json",
   data: JSON.stringify({ ParameterName: paramValue }),
});

It wasn't the reason in my case ... only removing async: false without changing to true fixed that
@Irfan in my case it was setting sync: false that helped!
to put async:true have reason to make it sync request for particular case. So removing it not a solution.
in my case async: true, solved the warning
C
Charlie

Visual Studio 2015/2017's live debugger is injecting code that contains the deprecated call.


I spent quite some time trying to figure out why I was seeing this warning; I figured I would share on the most appropriate SO question so others could save some time.
So very helpful. Thank-you. One can spend hours looking for the cause, as I have, thinking that it's one's own error in code somewhere when the cause is somewhere else entirely.
D
Dem Pilafian

Sometimes it's necessary to ajax load a script but delay document ready until after the script is loaded.

jQuery supports this with the holdReady() function.

Example usage:

$.holdReady(true);                              //set hold
function releaseHold() { $.holdReady(false); }  //callback to release hold
$.getScript('script.js', releaseHold);          //load script then release hold

The actual script loading is asynchronous (no error), but the effect is synchronous if the rest of your JavaScript runs after document ready.

This advanced feature would typically be used by dynamic script loaders that want to load additional JavaScript such as jQuery plugins before allowing the ready event to occur, even though the DOM may be ready.

Documentation:
https://api.jquery.com/jquery.holdready

UPDATE January 7, 2019

From JQMIGRATE:

jQuery.holdReady() is deprecated Cause: The jQuery.holdReady() method has been deprecated due to its detrimental effect on the global performance of the page. This method can prevent all the code on the page from initializing for extended lengths of time. Solution: Rewrite the page so that it does not require all jQuery ready handlers to be delayed. This might be accomplished, for example, by late-loading only the code that requires the delay when it is safe to run. Due to the complexity of this method, jQuery Migrate does not attempt to fill the functionality. If the underlying version of jQuery used with jQuery Migrate no longer contains jQuery.holdReady() the code will fail shortly after this warning appears.


S
Sonu K

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

jQuery has deprecated synchronous XMLHTTPRequest


d
dev101

@Webgr partial answer actually helped me debug this warning @ console log, shame the other part of that answer brought so many downvotes :(

Anyway, here is how I found out what was the cause of this warning in my case:

Use Chrome Browser > Hit F12 to bring DevTools Open the drawer menu (in Chrome 3 vertical dots in the upper right) Under Console > check Log XMLHttpRequests option Reload your page that was giving you the error and observe what happens on each ajax request in the console log.

In my case, another plugin was loading 2 .js libraries after each ajax call, that were absolutely not required nor necessary. Disabling the rogue plugin removed the warning from the log. From that point, you can either try to fix the problem yourself (e.g. limit the loading of the scripts to certain pages or events - this is way too specific for an answer here) or contact 3rd party plugin developer to solve it.

Hope this helps someone.


// , Thanks for the answer! This question only referred to Firefox. I'm interested to see that it occurred on Chrome. This only seems to remove the warning, rather than actually fixing the problem, though. Is that correct?
It seems that Chrome has more advanced stuff in the DevTools than Firefox version. The fact that it is not reported in Firefox does not mean it is not present. This completely fixed my problem, not just hidden it. I have removed the scripts from the problematic plugin and page that were 'reloaded' on each ajax call.
// , Do you think it is worth raising an issue with the Firefox developers?
No, not necessary. I have just re-tested my case with latest Firefox and "Synchronous XMLHttpRequest on the main thread..." warning was definitely reported in the console log, as well. So, it was, at least in my case, not a browser specific issue. Now, how you can use Firefox to debug XMLHttpRequest via Network tab, by watching the .js resources being called after each ajax request. Does the same thing, although it is more streamlined/filtered in Chrome. developer.mozilla.org/en-US/docs/Tools/Network_Monitor
Y
Yoweli Kachala

I have been looking at the answers all impressive. I think He should provide the code that is giving him a problem. Given the example below, If you have a script to link to jquery in page.php then you get that notice.

$().ready(function () {
    $.ajax({url: "page.php",
        type: 'GET',
        success: function (result) {
        $("#page").html(result);
   }});
 });

A
Andris

I get such warning in following case:

1) file1 which contains <script type="text/javascript" src="/javascript/jquery-1.10.2.js"></script>. Page has input fields. I enter some value in input field and click button. Jquery sends input to external php file.

2) external php file also contains jquery and in the external php file i also included <script type="text/javascript" src="/javascript/jquery-1.10.2.js"></script>. Because if this i got the warning.

Removed <script type="text/javascript" src="/javascript/jquery-1.10.2.js"></script> from external php file and works without the warning.

As i understand on loading the first file (file1), i load jquery-1.10.2.js and as the page does not reloads (it sends data to external php file using jquery $.post), then jquery-1.10.2.js continue to exist. So not necessary again to load it.


B
Bagrat Zakaryan

This is solved in my case.

JS

$.ajaxPrefilter(function( options, original_Options, jqXHR ) {
    options.async = true;
});

This answer was inserted in this link

https://stackoverflow.com/questions/28322636/synchronous-xmlhttprequest-warning-and-script


R
Radren

I got this exception when I set url in query like "example.com/files/text.txt". Ive changed url to "http://example.com/files/text.txt" and this exception dissapeared.


My issue also seems to have to do with the URL. I copied a script to a temporary URL to work on it, and that is when the error showed up. Not from the original URL.
C
Charles Merriam

And I got this exception for including one can.js script inside another, e.g.,

{{>anotherScript}}

This seems to be the main cause (loading additional and appending them to the in the DOM)
M
Misi

In a MVC application, I got this warning because I was opening a Kendo Window with a method that was returning a View(), instead of a PartialView(). The View() was trying to retrive again all the scripts of the page.


R
Ricardo Ruwer

It was happening to me in ZF2. I was trying to load the Modal content but I forgot to disable the layout before.

So:

$viewModel = new ViewModel();
$viewModel->setTerminal(true);
return $viewModel;

R
Rockwell Rice

Like @Nycen I also got this error because of a link to Cloudfare. Mine was for the Select2 plugin.

to fix it I just removed

 src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"

and the error went away.


d
drneel

In Chrome, press F12 Develomping tools-> press F1. See settings->general->Apperance: "Don't show chrome Data Saver warning"- set this checkbox. See settings->general->Console: "Log XMLHTTPRequest" - set this checkbox too.

Enjoy


C
Community

In my case this was caused by the flexie script which was part of the "CDNJS Selections" app offered by Cloudflare.

According to Cloudflare "This app is being deprecated in March 2015". I turned it off and the message disappeared instantly.

You can access the apps by visiting https://www.cloudflare.com/a/cloudflare-apps/yourdomain.com

NB: this is a copy of my answer on this thread Synchronous XMLHttpRequest warning and <script> (I visited both when looking for a solution)


m
mzonerz

I fixed this with below steps:

Check your CDN scripts and add them locally. Move your scripts includes into the header section.


a
a2f0

In my particular case I was rendering a Rails partial without render layout: false which was re-rendering the entire layout, including all of the scripts in the <head> tag. Adding render layout: false to the controller action fixed the problem.


g
gthuo

For me, the problem was that in an OK request, I expected the ajax response to be a well formatted HTML string such as a table, but in this case, the server was experiencing a problem with the request, redirecting to an error page, and was therefore returning back the HTML code of the error page (which had a <script tag somewhere. I console logged the ajax response and that's when I realized it was not what I was expecting, then proceeded to do my debugging.


A
Anirudha Gupta

The question raised in 2014 and it's 2019 so I guess it's good to look for better option.

You can simply use fetch api in Javascript which provide you more flexibility.

for example, see this code

fetch('./api/some.json')
    .then((response) => {
        response.json().then((data) => { 
            ... 
        });
    })
    .catch((err) => { ... });

is this pure js, no plugin require?
// , Do you really consider this a viable alternative to console.log()?
@NathanBasanese Sorry I didn't get your question, you means // for console.log ? or fetch or XMLHttpRequest?.
M
M lab

I found these problem cause early redirect page before javascript finish, in my case firebase rtdb set function.