My html file is as follows - a.html
<html>
<head>
<script id="js" type="text/javascript">
</script>
<script type="text/javascript">
function loadScript(src, cb){
alert('in');
//let script = document.getElementById('js');
let script = document.createElement( "script" )
script.src = src;
console.log(document.getElementById('js').src);
script.onload = cb();
//myFunc();
//cb();
document.getElementsByTagName( "head" )[0].appendChild( script );
alert('comp');
}
function callb(){
alert('in callb');
myFunc();
}
</script>
</head>
<body>
<input type="button" value="Click1" onclick = "loadScript('test.js',callb)"/>
<input type="button" value="Click2" />
</body>
</html>
My external js file is - test.js
function myFunc(){
alert("inside js file");
}
When i click the button Click1 I got
alert : in
alert : in callb
and then myFunc is undefined.
Hasnt the appended script tag loaded successfully? Please help me understand where am I going wrong. I am a novice in javascript.
cbis a reference to the function object.cb()calls that function object. You want to assign a function toscript.onloadsince you are telling the browser "call this function when you are done". When you usecb()you are (in theory) trying to assign the return value of the function toscript.onload. I.e. you are calling the function before the script was loaded andmyFuncdoes not exist yet.cbwith the argument:script.onload = function() { cb("some argument"); };.