PDA

View Full Version : Problem with dynamically added Javascript.


dipesh
04-24-2010, 08:28 AM
Here's my index.htm :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Test.</title>
<script language="JavaScript" type="text/javascript">

function funk(){
var head = document.getElementsByTagName("head")[0];
var tnode= document.createElement('script');
tnode.type = 'text/javascript';
tnode.src= '1.js'
head.appendChild(tnode);
doAlert('hello');
}

</script>
</head>
<body>
<A HREF="javascript:funk()">Click!</A>
<div id='pane' class='frame'></div>
</body>
</html>


And 1.js:
function doAlert(str){
alert("I said:"+str);
}

When Click! is clicked in index.htm, funk() is called which dynamically loads the javascript file 1.js. 1.js has the function doAlert() which is called from the last line of funk(). So when doAlert() is called from funk() for the first time, 1.js might not have been retrieved and the error "doAlert is not defined" is thrown.

So, how do I call doAlert() only after 1.js has been completely retrieved?

gizmo1650
04-24-2010, 06:34 PM
try importing 1.js using <script type="text/javascript" src="1.js">

TinyScript
04-24-2010, 09:17 PM
do this tnode.onload=function(){doAlert('hello');}




<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Test.</title>
<script language="JavaScript" type="text/javascript">

function funk(){
var head = document.getElementsByTagName("head")[0];
var tnode= document.createElement('script');
tnode.type = 'text/javascript';
tnode.src= '1.js'
head.appendChild(tnode);
tnode.onload=function(){doAlert('hello');}

}

</script>
</head>
<body>
<A HREF="javascript:funk()">Click!</A>
<div id='pane' class='frame'></div>
</body>
</html>

dipesh
04-25-2010, 08:54 AM
Thanks TinyScript, exactly what I needed.
Thanks a lot, you guys are amazing.