JsonpIt's a concept that almost everyone at the front has heard, but it's not that many who really know how to run at the bottom and can write one by hand. To be honest, jsonp is using the browser to allow cross-field loadingsThis feature of the cript script packs the data returned by api in a back-to-back function, and the browser executes this script "cross-domain". Today we're going to open up the principle and then handwritten the simplest。
How does jsonp cross-domain
The browser has an old co-source constraint: xhr cannot cross-domain request. But..CriptExcept that it can point to any domain name and the browser loads the execution. Jsonp just took the space. When the front-end sends a request to a cross-domain url, tell the service that "pack the data in my foo function" and the service returns a script clip like foo (name: "agnes", age:25}), the browser loads the execution, and the data is in hand. There's no cors head in the whole process. It's pure sCript tag works. Content-type is application/javasI don't know。
Front-end dynamic creations on hands-onCript node is hung on body, and the return function name is exposed to window, and the url contains the callback = foo parameter. The service recognizes the callback of json after you have reached the callback. The front end clears the temporarys as soon as we get the data back in the loopThe functions on the cript node and window end with a call。
What does a handwritten jsonp have to notice
There are three core details. Revert function name mustRandomGenerate, spell time, do not write dead, and prevent renaming or multiple calls to overwhelm the page. The second is..TimerIt's..Cript tags failed to load without triggering the error event in many browsers, having to set a five-second timeout manually, clearing the scene without returning the call. The third is to clean upDelete window [fnname], and remove the domsCript node, otherwise memory will slowly rise。
Write a very simple version of about 30 lines: generate random functions with the name window, url, new sCript into body, back to resolve promise, timeoutline. Now the new project is running out of jsonp and cores plusfetch basically covers the vast majority of the scenes, but the old interface, the government system, and some third party sdk are still using this. Interviews are cross-border and handwritten to score。
Got itCript tags load this bottom logic across domains and then touch the new scenarios of cors, fetch, and websocket, which will work in contrast. The rationale is not complex, and it is difficult in terms of random names, time overruns and security。










