Javascript onload and script callback functions, which takes the precedence? -
i'm loading external script uses callback function, returns specific data. if data not received error should displayed.
here code i've made:
<script> //setting initial state function work once var visitors_loaded=false; var my_callback = function( data ) { if (visitors_loaded) return 0; if (data) { //success: callback function called , has 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 can see... many things can go wrong script, naturally added onerror event. on error event fires if change host name or domain of script non-existent.
however, if make changes url of script, can still connects server , fires onload event instead. callback function not called invalid requests, added onload handler well.
now problem is, if loaded , data returned, fire both, callback function , onload. have noticed callback function triggered before onload , set visitors_loaded variable handler function called once.
so far works in js fiddle , offline site wonder if expected behavior? json_callback function have precedence before onload handler?
will json_callback function have precedence before onload handler?
if external script calls my_callback
synchronously yes.
the scripting
section in official html5 specification describes how these things supposed work. specification quite general , has deal lot of details conserning encoding, cors, ignore-destructive-writes counter
, on. question don't care these specifics.
in step 4 there note:
note: script compiled , executed.
and in step 7 load
event fired:
fire simple event named load @ script element.
so specification defines load
event fired after script has been executed.
as see specification tells why onerror
event not fired if change url. error
event created if loading script fails. requests https://api.clicky.com/api/stats/
return http 200 status. invalid urls return xml , syntaxerror thrown. not cause onerror
handler triggered.
as others have mentioned if callback called asynchronously can call callback after onload
event. don't see reason why async in external script.
Comments
Post a Comment