


Solution to the UI thread blocking problem caused by jQuery synchronized Ajax
This article mainly introduces the UI thread blocking problem and solutions caused by jQuery synchronized Ajax. It has certain reference value. Those who are interested can learn about it
As the saying goes, if you don't seek death, you won't die. I committed suicide today and wrote a relatively stupid function. I encountered the UI thread blocking problem caused by synchronized Ajax. I will record it here.
The reason is this, because there are multiple similar asynchronous request actions on the page. In line with the principle of improving code reusability, I encapsulated a function named getData, which receives different parameters and only Responsible for obtaining data and then returning the data. The basic logic stripped out is as follows:
function getData1(){ var result; $.ajax({ url : 'p.php', async : false, success: function(data){ result = data; } }); return result; }
The ajax here cannot be asynchronous, otherwise when the function returns, the result has not been assigned a value, and an error will occur. So I added async:false. It seems like there is no problem. I can get the data normally by calling this function.
$('.btn1').click(function(){ var data = getData1(); alert(data); });
Next, I need to add another function. Since the ajax request takes a certain amount of time, I need to have a loading effect on the page before making the request, that is, display a You must have seen this gif picture of "Loading". So my processing function becomes like this:
$('.btn1').click(function(){ $('.loadingicon').show(); var data = getData1(); $('.loadingicon').hide(); alert(data); });
Display the loading image before the request, and hide it after the request is completed. There seems to be no problem. In order to see the effect clearly, my p.php code sleeps for 3 seconds, as follows:
<?php sleep(3); echo ('aaaaaa'); ?>
But a problem occurred when I ran it. When I clicked the button, it did not work as expected. The loading picture appears like this, but the page does not respond at all. After troubleshooting for a long time, I found the reason, which is async:false.
The browser's rendering (UI) thread and js thread are mutually exclusive. When executing js time-consuming operations, page rendering will be blocked. There is no problem when we execute asynchronous ajax, but when set to a synchronous request, other actions (the code behind the ajax function, and the rendering thread) will stop. Even if my DOM operation statement is the sentence before the request is initiated, this synchronization request will "quickly" block the UI thread without giving it time to execute. This is why the code fails.
setTimeout solves the blocking problem
Now that we understand where the problem is, let’s find a solution. In order to prevent the synchronous ajax request from blocking the thread, I thought of setTimeout, put the request code in sestTimeout, and let the browser restart a thread to operate. Wouldn't the problem be solved? Ever since, my code has become like this:
$('.btn2').click(function(){ $('.loadingicon').show(); setTimeout(function(){ $.ajax({ url : 'p.php', async : false, success: function(data){ $('.loadingicon').hide(); alert(data); } }); }, 0); });
The second parameter of setTimeout is set to 0, and the browser will execute it after a set minimum time. . No matter what, let's run it first and see.
The result loading picture is displayed, but! ! ! Why doesn't the picture move? It's obviously an animated gif. At this time, I quickly thought that although the synchronization request was delayed, it would still block the UI thread during its execution. This blocking is so awesome that even the gif image doesn’t move and looks like a static image.
The conclusion is obvious. SetTimeout treats the symptoms but not the root cause. It is equivalent to making the synchronization request "slightly" asynchronous. Then it will still enter a synchronization nightmare and block the thread. The plan failed.
It’s time to use Deferred
After version 1.5, jQuery introduced the Deferred object, which provides a very convenient generalized asynchronous mechanism. For details, please refer to this article http://www.jb51.net/article/54762.htm.
So I rewrote the code using the Deferred object, as follows:
function getData3(){ var defer = $.Deferred(); $.ajax({ url : 'p.php', //async : false, success: function(data){ defer.resolve(data) } }); return defer.promise(); } $('.btn3').click(function(){ $('.loadingicon').show(); $.when(getData3()).done(function(data){ $('.loadingicon').hide(); alert(data); }); });
You can see that I removed async:false in the ajax request, that is to say , this request is asynchronous again. Please also pay attention to this sentence in the success function: defer.resolve(data). The resolve method of the Deferred object can pass in a parameter of any type. This parameter can be obtained in the done method, so the data we requested asynchronously can be returned in this way.
At this point, the problem has been solved. Deferred objects are so powerful and convenient, we can take advantage of them.
All my test codes are as follows. Interested students can use them to test:
<button class="btn1">async:false</button> <button class="btn2">setTimeout</button> <button class="btn3">deferred</button> <img class="loadingicon" style="position:fixed;left:50%;top:50%;margin-left:-16px;margin-top:-16px;display:none;" src="loading2.gif" alt="正在加载" /> <script> function getData1(){ var result; $.ajax({ url : 'p.php', async : false, success: function(data){ result = data; } }); return result; } $('.btn1').click(function(){ $('.loadingicon').show(); var data = getData1(); $('.loadingicon').hide(); alert(data); }); $('.btn2').click(function(){ $('.loadingicon').show(); setTimeout(function(){ $.ajax({ url : 'p.php', async : false, success: function(data){ $('.loadingicon').hide(); alert(data); } }); }, 0); }); function getData3(){ var defer = $.Deferred(); $.ajax({ url : 'p.php', //async : false, success: function(data){ defer.resolve(data) } }); return defer.promise(); } $('.btn3').click(function(){ $('.loadingicon').show(); $.when(getData3()).done(function(data){ $('.loadingicon').hide(); alert(data); }); });</script>
PS: Is Firefox optimized?
The above problems have been tested in chrome and IE9 and the conclusions are consistent. But when I tested it in Firefox, synchronized ajax did not block the UI thread, which means that this problem does not exist at all. I tested it with other codes. In Firefox, the js thread will indeed block the UI thread. There is no doubt about this. One possible guess is that Firefox has optimized synchronized ajax. I have not yet learned what the fact is. If anyone knows, please give me some advice.
The above is the detailed content of Solution to the UI thread blocking problem caused by jQuery synchronized Ajax. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

To avoid thread starvation, you can use fair locks to ensure fair allocation of resources, or set thread priorities. To solve priority inversion, you can use priority inheritance, which temporarily increases the priority of the thread holding the resource; or use lock promotion, which increases the priority of the thread that needs the resource.

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Thread termination and cancellation mechanisms in C++ include: Thread termination: std::thread::join() blocks the current thread until the target thread completes execution; std::thread::detach() detaches the target thread from thread management. Thread cancellation: std::thread::request_termination() requests the target thread to terminate execution; std::thread::get_id() obtains the target thread ID and can be used with std::terminate() to immediately terminate the target thread. In actual combat, request_termination() allows the thread to decide the timing of termination, and join() ensures that on the main line

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.
