How to avoid repeated ajax requests?

      In the process of front-end development, if you do not pay attention to restrictions and blockades, there will often be a lot of repeated Ajax requests, resulting in a lot of pressure on the server. Today, Xiaoqian will come to provide you with a few solutions.

      1. Interception at the UI level

      When the user moves the small hand to make a fortune and clicks the button, the button is immediately disabled and the waiting animation is turned on. If a successful response from the server is received, then the animation is hidden. The timeout must be set, and the time should not be too long, if it is too long , The user will swear.

1

2

      2. Blocking at the JS level

      (1) Violent click

      If the user continuously violently clicks the button, we can do it through the function anti-shake. In fact, it is the combination of setTimeout and clearTimeout in the closure. Continuous clicks will clear the last click processing function, and our ajax request will be the last click Send it out later.

3

      (2) Fast switching between multiple tab pages

      Fast switching of multiple tab pages is also a common scenario. If a user quickly switches from tab1 to tab2, and then quickly switches from tab2 to tab1, it is inevitable that the same tab will have to initiate multiple requests repeatedly.

      Another problem is that in a single-page application, the dom structure is destroyed after the tab is switched. At this time, the data comes back. If the destroyed dom is operated, the console will report an error. In vue, react and other dom frameworks that do not require manual operation by the developer, if we modify the state, the following warning message will be reported, which is difficult to read.

4

      The idea to solve this problem is to abort the previous request. The XMLHttpRequest object has an abort method, which can be called directly.

      If you use a third-party request library, such as axios, we can create a cancel token for our request, set a token for each request, and before the page is switched or the component is destroyed, we only need to cancel through source.cancel. , In fact, the principle is still achieved through the abort method of xhr.

      The specific code and process can be referred to as follows.

5

      For different usage scenarios, we can flexibly combine the above solutions. I don’t know if we can save the heart of the server if we do this. I think of running in the sunset again. It was a beautiful encounter between me and the server, and also our lost youth. ......


This article is from Qianfeng Education , please indicate the source for reprinting


Guess you like

Origin blog.51cto.com/15128693/2676906