[jquery] 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"?

This question is related to jquery debugging firefox backbone.js console.log

The answer is


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/


I fixed this with below steps:

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

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.


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

{{>anotherScript}}

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.


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.


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) => { ... });

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

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.


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

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)


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


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.


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;

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.


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


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


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.


  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


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.


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


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to debugging

How do I enable logging for Spring Security? How to run or debug php on Visual Studio Code (VSCode) How do you debug React Native? How do I debug "Error: spawn ENOENT" on node.js? How can I inspect the file system of a failed `docker build`? Swift: print() vs println() vs NSLog() JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..." How to debug Spring Boot application with Eclipse? Unfortunately MyApp has stopped. How can I solve this? 500 internal server error, how to debug

Examples related to firefox

Drag and drop menuitems Class has been compiled by a more recent version of the Java Environment Only on Firefox "Loading failed for the <script> with source" Selenium using Python - Geckodriver executable needs to be in PATH Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property How to use the gecko executable with Selenium Selenium 2.53 not working on Firefox 47 Postman addon's like in firefox Edit and replay XHR chrome/firefox etc? How to enable CORS on Firefox?

Examples related to backbone.js

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document' JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..." Error: getaddrinfo ENOTFOUND in nodejs for get call npm install error from the terminal Lodash .clone and .cloneDeep behaviors Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined Angular.js vs Knockout.js vs Backbone.js How to convert 1 to true or 0 to false upon model fetch Origin http://localhost is not allowed by Access-Control-Allow-Origin What is two way binding?

Examples related to console.log

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..." Can't access object property, even though it shows up in a console log How can I add a variable to console.log? Printing to the console in Google Apps Script? How can I get the full object in Node.js's console.log(), rather than '[Object]'? Node.js: printing to console without a trailing newline? What is console.log?