I am loading an external script that uses a callback function that returns some specific data. If this data is not received, an error should be displayed.
Here is the code I made:
<script> //setting initial state so that function will only work once var visitors_loaded=false; var my_callback = function( data ) { if (visitors_loaded) return 0; if (data) { //success: callback function is called and it has a proper data visitors_loaded=true; alert(JSON.stringify(data)); } else alert ('error'); //something went wrong }; </script> <script onload="my_callback(null)" onerror="my_callback(null)" src="https://api.clicky.com/api/stats/4?site_id=32020&sitekey=9a19b1a4d1171193&type=visitors&date=this-month&output=json&json_callback=my_callback"></script>
As you can see ... many things can go wrong with the script, so I naturally added an onerror event. This error event actually fires if you change the hostname or domain of the script to something that does not exist.
However, if you only make changes to the script URL, it can still connect to the server and instead fire the onload event . My callback function will not be called for these invalid requests, so I added an onload handler.
Now the problem is that if all loaded normally and the data was returned, it will run both the callback function and the load. I noticed that the callback function runs before loading and sets the visitor_loaded variable, so that the handler function is called only once.
While it works fine in the JS script and my standalone site, but I wonder if this is the expected behavior? Will this json_callback function always take precedence over the onload handler?
https://jsfiddle.net/5sfk9ht5/4/
source share