Using synchronous XMLHttpRequest on the main thread is no longer recommended when working with embedded JavaScript in code

I've implemented a basic Ajax function on my website, but I'm encountering a warning in the console.

The warning states:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

What exactly does this mean and how can I prevent it?

function readTextFile(file) {
    var rawFile = new XMLHttpRequest();
    var allText = "";
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                allText = rawFile.responseText;
            }
        }
    }
    rawFile.send(null);
    return allText;
}

function load() {
    var allText = readTextFile('drinks.json');
    var mydata = JSON.parse(allText);
    var div = document.getElementById('cocktaillist');

    div.innerHTML = "";
    for (var i = 0; i < mydata.length; i++) {
        div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
    }
}

Answer №1

To improve your code efficiency, consider switching to asynchronous Ajax requests instead of synchronous ones. Synchronous requests can negatively impact the user experience, so it's best to avoid them altogether.

Make sure to implement callback functions in your code for better handling. Here is a comparison:

function fetchData(url, successCallback) {
    let request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.onreadystatechange = function () {
        if (request.readyState === 4) {
            if (request.status === 200) {
                successCallback(request.responseText);       
            } else {
                console.log("Unexpected response status: " + request.status);
            }
        }
    };
    request.send(null);
}

function initialize() {
    fetchData('data.json', function (responseData) {  
        let data = JSON.parse(responseData);
        let container = document.getElementById('datalist');
        container.innerHTML = "";
        for (let i = 0; i < data.length; i++) {
            container.innerHTML += "<p class='item' id="+i+">"+ data[i].name +"</p><br>";
        }
    });
}

Answer №2

The following message was observed:

It has been advised that using synchronous XMLHttpRequest on the main thread is no longer recommended due to its negative impact on user experience.

This is a cautionary notice regarding the use of synchronous requests in JavaScript, as it disrupts the asynchronous behavior and hinders the user interface, particularly under poor network conditions.

To address this issue, ensure you have set the third parameter of rawFile.open() to true and have included a rawFile.onreadystatechange callback to handle responses appropriately. The rest of your code appears to be in good order.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for streamlining distinct states and generalized state in UI Router

I've set up the following configuration in my JS app under the $stateProvider section using angular ui-router: .state('login', { url: '/login', templateUrl: 'app/login/login.tmpl.html', controller: &apo ...

The hide() and on() methods are not compatible with Internet Explorer (IE)

My code is working fine on Google Chrome, but for some reason it's not functioning properly on Internet Explorer (IE). I'm using IE11 and really need this to work on all browsers. Please help me figure out what's going wrong here. $(' ...

Prevent the Esc key from closing panel in jQuery Mobile

As per the jQuery Mobile documentation: "If you click the link that opened the panel, swipe left or right, or tap the Esc key, the panel will close. By default, panels can also be closed by clicking outside of the panel onto the page contents." Visit t ...

JavaScript promise will return a value that is undefined

Trying to pass a jQuery ajax request through a promise like this: var foo; foo = bar().then(function(response) { console.log("Success!", response); console.log(foo[0].bool); }, function(error) { console.error("Failed!", error); }); console.lo ...

Eliminate the unnecessary code repetition in my functions using Typescript

I have 2 specific functions that manipulate arrays within an object. Instead of repeating the same code for each array, I am looking for a way to create reusable functions. Currently, my functions look like this: setLists(): void { if (this.product.ord ...

What is the best way to apply margins to a nested div element in relation to its parent div element using CSS?

My Coding Dilemma: #b { width: 700px; height: 150px; margin-top: 10%; margin-left: 20%; text-align: center; border: 2px solid black; } .block { width : 10%; height : 10%; border: 2px solid black; padding: 40px 40px; margin: inheri ...

Looking for assistance with transferring a JavaScript array to my PHP script

Is there an easier way to transfer a JavaScript array to a PHP file? I've seen examples of using AJAX for this task, but I'm wondering if there's a simpler method. Below is a snippet of the code I'm working with: <html> <hea ...

Is there a built-in event in Jquery UI tabs for when the tabs are collapsed?

Which event in jquery ui can I utilize to detect when a panel collapse has finished on the browser? I require this information to perform calculations based on the screen layout after the collapse has occurred. If I use the select or show event callbacks, ...

Create a leaflet rectangle using coordinates derived from user mouse actions

I want to implement a feature where the user can set one corner of a rectangle when clicking the mouse button, and then upon releasing the mouse button, set the coordinates for the opposing corner and draw the rectangle. Here is my attempt using JavaScript ...

What is the method for setting a variable to an object property's value?

I am currently working on a React app and I have an object structured like this: state = { property1: 'value', property2: 'value', property3: 'value', property4: 'value', } I am trying to write a fu ...

The Firefox extension is in need of Google Chrome for compatibility

Currently, I am developing a Firefox extension that displays SSL certificate details. My goal is to only view the certificate information without making any alterations. I am attempting to utilize this specific code example, however, the JavaScript code ha ...

Does Angular perform tree shaking on a service that is provided at the root level, as long as it is not explicitly injected into a component instance?

Suppose we implement a service similar to this as part of a library: @Injectable({ providedIn: 'root' }) export class ChartJSProvider { constructor() { Chart.register(...registerables); } } and our application makes use of the aforem ...

Order objects in a JavaScript array

Recently, I came across a list of student data fetched from an API: const Studentdata = { "StudentName1": { "active": true, "gender": "male" }, "StudentName2": { "active": false, "gender": "male" }, "S ...

Is there a way for me to automatically close the navbar by clicking anywhere on the body of

Here is the structure of my navigation bar: <div id="mySidenav" class="sidenav"> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a> <span ...

Unable to retrieve a response, the operation `users.findOne()` has exceeded the buffering time limit of 10000ms

I encountered an issue when attempting to make a POST login request. The frontend is deployed on Netlify here, and the backend is deployed on Heroku here. Here are my backend logs . I am receiving `users.findOne()` buffering timed out after 10000ms in ...

Make sure to always select the alternative option in ajax

I am trying to create a condition where if the value of id=type_investor is either 1 or 6, an email should be sent using a different controller. Here is my complete code: function (isConfirm) { if (!isConfirm) return; $.ajax({ ...

Is it possible to fulfill a promise within an if statement?

I'm fairly new to using promises in JavaScript, and I am currently facing an issue where a function needs to execute before running some additional code in another function. The problem arises when the promised function includes an if statement that l ...

Jesting around with mocking console.error leads to test failures

The Issue: Currently, I am working on testing React components using Jest and Enzyme. In order to check for properties in development, I have incorporated the prop-types module. The prop-types module relies on console.error to alert when mandatory props a ...

Undefined output in Typescript recursion function

When working with the recursion function in TypeScript/JavaScript, I have encountered a tricky situation involving the 'this' context. Even though I attempted to use arrow functions to avoid context changes, I found that it still did not work as ...

The click event for getelementbyid() function is malfunctioning

I need assistance with a website I am creating that plays audio when a certain condition is met. Specifically, I want the audio to play if x falls within a specific range of numbers, but also continue playing if x does not fall within that range after th ...