Recently, a buddy was working on an Ajax long connection project. The page needed to maintain a long connection with the server, and the connection needed to be re-requested after the connection timed out. During the process, he asked me what I wanted to use, and I told him to use it without even thinking about it. jQuery. Doesn't jQuery have ajaxSuccess ajaxError objects? Wouldn't it be nice to re-request after the request is completed or the request fails?
But then he told me that he didn’t use jQuery and wrote the XMLhttprequest manually. He told me that it was written in jquery at first, and there were no problems during the testing process. But later I accidentally discovered that after the page was open for a long time, the browser resource usage was very high, causing insufficient memory and crashing. Later, packet capture analysis found that each jquery Ajax request will create an xmlHttprequest object. Theoretically, the request for a long connection is an infinite recursion, and the number of requests is very large. However, since each request will create a new xmlhttprequest, Moreover, jquery does not automatically recycle resources, causing memory overflow.
By looking at the jquery API, I found that jquery also has a complete object, which is a callback function after the request is completed (called after the request is successful or failed). There are two parameters XMLHttpRequest and textStatus at the same time. Therefore, we only need to manually recycle the returned XMLHttprequest object after the request is completed. The code is as follows: