Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

wait for script to load

Status
Not open for further replies.

c3f8

Programmer
Jul 16, 2007
8
PT
hi there.

Is there any way of loading dynamically a script and wait for him to load?

I am using google api but i just want to load the script when i press a button but i need for the script to load to continue processing.


thanks
 
Hi

To find out when the script is loaded, you need either a "feed back" from the script itself, or to check periodically the existence of something created by that script.

For loading the script file :
Code:
[b]var[/b] s=document.createElement([i]'script'[/i]);
s.src=[i]'where/is/your/script.js'[/i];
[b]var[/b] h=document.getElementsByTagName([i]'head'[/i])[0];
h.appendChild(s);
Tested in Mozillas, Opera, Safari and Explorer.

Feherke.
 
var headID = window.document.getElementsByTagName("HEAD")[0];
var newScript = window.document.createElement("SCRIPT");
newScript.type = "text/javascript";
newScript.src = "teste.js";
headID.appendChild(newScript);

alert(3);

this is my code. the "teste.js" just have an alert("teste.js").

But the alert(3) always executes first than my script.
 
Hi

Of course, [tt]alert(3)[/tt] executes immediately. The JavaScript code just creates the object, then the browser handles the request. Of course, the request is handled transparently, without letting the JavaScript code to know anything about.
Code:
<html>
<head>
<title></title>
<script type="text/javascript">
[red]var inter;[/red]
function hmm()
{
  var headID = window.document.getElementsByTagName("HEAD")[0];
  var newScript = window.document.createElement("SCRIPT");
  newScript.type = "text/javascript";
  newScript.src = "js.js";
  headID.appendChild(newScript);
  [red]inter=window.setInterval('wait4load()',100);[/red]
}
[red]function wait4load()
{
  if (imloaded) {
    window.clearInterval(inter);
    alert('3');
  }
}[/red]
</script>
</head>
<body onload="hmm()">
</body>
</html>
Code:
alert('teste.js');

[red]var imloaded=true;[/red]

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top