1

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.

4
  • Thanks @FelixKling. In this context how is cb different from cb()? Commented Mar 24, 2020 at 20:14
  • cb is a reference to the function object. cb() calls that function object. You want to assign a function to script.onload since you are telling the browser "call this function when you are done". When you use cb() you are (in theory) trying to assign the return value of the function to script.onload. I.e. you are calling the function before the script was loaded and myFunc does not exist yet. Commented Mar 24, 2020 at 20:15
  • @FelixKling Quick question. What if cb is a function that takes an argument? In such a case how can the argument be passed when calling for script.onload? Commented Mar 24, 2020 at 21:11
  • You can simply create and assign another function which calls cb with the argument: script.onload = function() { cb("some argument"); };. Commented Mar 24, 2020 at 21:27

1 Answer 1

1

script.onload = cb(); should be script.onload = cb;. The former calls cb() right then and there and assigns the return value to script.onload. In other words you are calling the callback before the script finished loading, at which point the function myFunc doesn't exist yet of course.

Also don't use alert for debugging because it's blocking and can verify well impact how your code behaves when dealing with async i/o.

Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks! I replaced all alerts with console.log and I got 'comp' before 'inside js file'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.