This is the third day of my participation in the August More text Challenge. For details, see:August is more challenging

‘XXX is not a function’ is not a function (‘ XXX is not a function ‘is not a function) is not a function (‘ XXX is not a function’ is not a function)

details

Obviously, this is a callback function for a JSONP request, such as:

$.ajax({
  url: 'https://foo.com/my/info'.dataType: 'jsonp'.jsonp: 'jsonpcb'.timeout: 5000.success: function(data) {
    console.log(data);
    // some logic
  },
  error: function(e) {}})Copy the code

The server then returns the contents:

JSONP_1628781407874({"code":0."data": {"name":"Jack"."age":22}})
Copy the code

Then why will the runtime error be triggered? By looking at the distribution of the request duration of this interface, it is found that some users’ duration will reach 10 seconds or even longer. Uncaught TypeError: JSONP_1628781407874 is not a function

Obviously, the jSONP request method will remove the method JSONP_1628781407874 declared in window after the wait time exceeds timeout.

The solution

Plan a

In this case, the most straightforward thing to do is not to let it remove the callback function. However, this is obviously problematic because if a page has a large number of JSONP requests, the window will have more and more of these callbacks hanging over it, and the callbacks themselves will be used once.

Therefore, this scheme is not feasible.

Scheme 2

  • Define a common handler for timeouts (including logic for reporting timeout events)
  • The delete callback is performed on success or error, and on timeout, a variable of the callback is referred to the timeout generic handler defined above. When the timeout request returns data, the reporting logic is executed.

Scheme is feasible

Plan 3

Keep the same jSONP processing logic, but require the server’s JSONP interface to return with an extra layer of try-catch code, such as:

try { JSONP_1628781407874({"code":0."data": {"name":"Jack"."age":22}})}catch(e) {}
Copy the code

So that even if the timeout causes the callback function to be deleted, it does not trigger a run error.

The scheme is feasible, but it needs the cooperation of back-end colleagues

conclusion

Finally, let’s take a look at how JSONP works

  • Create and insert a script tag declaring the path to request the script static resource (that is, the path of the interface that supports JSONP)
    • As an argument to the path, pass the name of the function that performs the callback to the server as agreed with the backend colleagues
  • (If any) Specifies the timeout period, sets the timer, and performs error handling when the specified timeout period is reached
  • {server} receives the request, gets the result, and returns the data to the front page wrapped in the function name received earlier
  • When the return data is received, the callback function is executed
  • Delete the callback function