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

22

421

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"?

Superior answered 8/7, 2014 at 18:39 Comment(8)
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.Holloman
I'm not sure it's making an ajax call. Would it help if I included a screenshot?Superior
xmlhttprequest is an ajax request, basically.Holloman
Well, I'm not sure, either. I will include some context. I would really like to get this resolved. The International Network in all its knowledge and splendour, may it live for ever, has not produced any answer useful to my case.Superior
<script>$.ajaxPrefilter(function( options, originalOptions, jqXHR ) { options.async = true; });</script> this will removes the warning. You can see here for same issue.Burushaski
I had the same error message and fixed when I corrected an another problem in my code.Zendavesta
I just used get instead of post, it helped. jQuery.Samp
Beware. In my case it was not my code, but Last Password add-on for Google Chrome that was causing this warning.Hickson
M
304

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/

Melamie answered 12/2, 2015 at 13:0 Comment(12)
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 :).Adenectomy
For this project, I did, in fact, use JQuery.Superior
@37coins, if this was the answer; mark it as so.. and replace javascript tag with jQuery.Guernica
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.Maintop
just FYI jQuery getScript breaks caching. I think .ajax will do same and allow for cachingThundery
If you are using Angular and getting the error, it happens if you put <script type="text/ng-template" id="template.html"> in your template / partial fileBlather
Please Google: link this word SOLVED ! with this OP and help people like me!!! XDXDXD (By the way, I've been searching for answers months and months and it's a pity that the question about 'console.log' avoided me to locate this before, and very embarrassing for me to discover the problem was occasioned by something as simple as that). Thx.Wiencke
Wouldn't using the async attribute in the script tag prevent jQuery from making a synchronous call?Randirandie
@YusrilMaulidanRaji tomorrow, indeed, never came. In fact, our planet has completed one more rotation around our local star since your very own comment was added, and still no marking of this answer as the approved one.Eteocles
I am getting Uncaught TypeError: jQuery.easing[jQuery.easing.def] is not a function after using $.getScript(url); as above.Assuan
@ShanikaEdiriweera You might be missing an a script tag, or import? It sounds like jQuery.easing or some part of it is not being pulled across.Melamie
I was unable to reproduce this issue using both success() and done(). Possibly only present in older versions of the library? I tested on 1.12.4.Shandishandie
A
81

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.

Accidie answered 20/11, 2014 at 17:45 Comment(4)
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?Guernica
@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.Accidie
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.Guernica
They should add an about:flag to enable it for local debugging. Sync XHR can be very useful for tooling/debug frameworks running localhost.Didache
R
73

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 }),
});
Rotor answered 19/3, 2015 at 13:41 Comment(4)
It wasn't the reason in my case ... only removing async: false without changing to true fixed thatPortray
@Irfan in my case it was setting sync: false that helped!Sajovich
to put async:true have reason to make it sync request for particular case. So removing it not a solution.Pancratium
in my case async: true, solved the warningFleabitten
Z
42

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

Zina answered 2/4, 2017 at 0:34 Comment(4)
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.Zina
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.Recusant
Thank you, so can you tell me how to solve this warning?Poop
Once the debugger is detached, it won't get injected and wont be a problemZina
U
23

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.

Umberto answered 26/9, 2015 at 23:52 Comment(0)
F
20

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

France answered 26/5, 2017 at 17:27 Comment(0)
T
13

@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:

  1. Use Chrome Browser > Hit F12 to bring DevTools
  2. Open the drawer menu (in Chrome 3 vertical dots in the upper right)
  3. Under Console > check Log XMLHttpRequests option
  4. 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.

Tantamount answered 5/2, 2017 at 23:42 Comment(4)
// , 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?Superior
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.Tantamount
// , Do you think it is worth raising an issue with the Firefox developers?Superior
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_MonitorTantamount
T
8

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);
   }});
 });
Thyroxine answered 15/10, 2015 at 10:6 Comment(0)
S
7

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.

Septic answered 23/6, 2015 at 16:29 Comment(0)
M
6

This is solved in my case.

JS

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

This answer was inserted in this link

https://mcmap.net/q/48350/-synchronous-xmlhttprequest-warning-and-lt-script-gt

Moina answered 28/12, 2017 at 13:41 Comment(0)
Z
5

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.

Zooid answered 14/4, 2015 at 9:35 Comment(1)
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.Ci
W
5

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

{{>anotherScript}}
Windtight answered 25/5, 2015 at 21:22 Comment(1)
This seems to be the main cause (loading additional <scripts> and appending them to the <head> in the DOM)Trakas
N
5

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.

Niobe answered 2/7, 2015 at 8:41 Comment(0)
D
5

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;
Dainedainty answered 3/8, 2015 at 23:14 Comment(0)
O
5

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.

Obmutescence answered 7/12, 2015 at 14:17 Comment(0)
K
5
  1. In Chrome, press F12
  2. Develomping tools-> press F1.
  3. See settings->general->Apperance: "Don't show chrome Data Saver warning"- set this checkbox.
  4. See settings->general->Console: "Log XMLHTTPRequest" - set this checkbox too.

Enjoy

Kickshaw answered 12/4, 2016 at 12:15 Comment(0)
S
4

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)

Sacellum answered 19/5, 2015 at 17:21 Comment(0)
E
3

I fixed this with below steps:

  1. Check your CDN scripts and add them locally.
  2. Move your scripts includes into the header section.
Eduction answered 21/10, 2015 at 7:30 Comment(0)
P
3

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.

Ptosis answered 9/6, 2017 at 22:48 Comment(0)
R
3

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.

Rickie answered 5/2, 2018 at 6:41 Comment(0)
D
3

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) => { ... });
Deflocculate answered 3/1, 2019 at 6:2 Comment(4)
is this pure js, no plugin require?Considerate
@Considerate Yes, Please look at this developers.google.com/web/updates/2015/03/introduction-to-fetchDeflocculate
// , Do you really consider this a viable alternative to console.log()?Superior
@NathanBasanese Sorry I didn't get your question, you means // for console.log ? or fetch or XMLHttpRequest?.Deflocculate
E
-1

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

Eiffel answered 24/9, 2021 at 3:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.