I am making a cross-domain JSON(P) call by using JavaScript to add a <script>
tag to the DOM with that URL I want included as the src
. The script being loaded has a callback that calls a function on my page, and the data I want is returned as an argument to the function.
There are 2 catches, though:
- Sometimes the JSONP page will return a 400 or 404 error.
- The same JSONP file can be requested multiple times on the same page (each time returning different data)
So, I need to detect when the callback function is not fired (which would indicate that the JSONP file returned an error), but I also need to account for the fact that the same file can be requested twice. Essentially, I need to detect the error in loading the page, but I have to do it before the other files finish loading. And yes, the files should be loaded (or return an error) in the correct order.
One (inefficient) solution:
I could make a bunch of different functions that are requested for each different file load (eg. callbackFunction0, callbackFunction1, etc). That way, I can simply determine when one of the functions didn't fire and have my JavaScript act off of that. However, this would take up a lot of space an be inefficient because I would have to have one callbackFunction for the maximum time the script would be loaded on the same page (this number has no definite value, though, so if I only made 15 functions and the script was requested 20 times, errors would occur).
This was kind of difficult to explain, but hopefully you got the idea. Thanks.