I have Js Src code that contain Jsonp api functions. Where ever this Js Src code got printed i got to check first if the “api tag” printed already , if it did -> execute the api function , if the “api tag” have not got printed yet , wait for the tag to get printed on the screen and then execute the api functions.
for example i have this code
<html>
<head>
<!-- js code - contain Jsonp functions -->
<script type="text/javascript" src="jsonp.js"></script>
</head>
<body>
<!-- when this newtag get print , the function starts -->
<newtag:api size="small">myNewTag</newtag:api>
</body>
I don’t know where the user will decide to put the JS code , it may be in the head , body or in the middle of the page , since i have this mystery i cant do something like this :
<newtag:api size="small">myNewTag</newtag:api>
<script> startJsonp(); </script>
because if the js code did not printed yet the order will not be execute.
and if the Js code got print in the head so it will not work since the “api tag” did not got printed yet.
to make the api work i need the “api tag” to be printed on the screen already for the Jsonp functions to work.
what i can do to solve this?
what is the porpoise to write JS function like that?
(function(){
// do something
})();
thank you so much!
There are several solutions for this problem:
Using jQuery’s ready function. E.g.:
jQuery.ready(function(){ startJsonp(); })
Using window.onload. The problem is that you can unintended override another window.onready function. E.g.:
window.onready = startJsonp();
Using document.addEventListener and document.attachEvent. Eg.:
if (document.addEventListener){
document.addEventListener(‘load’, startJsonp, false);
} else if (el.attachEvent){
document.attachEvent(‘onload’, startJsonp);
}