First, there are a few syntax errors in your code that need to be fixed.
Then, You will need to call the function after it is defined (or in the same <script>
tag). Function hoisting does not hoist print1()
in time. That is because the browser tries to execute the script as soon as it encounters it. This means when the browser sees <script>print1()</script>
, it is not even aware of the rest of the file.
So you need to invoke print1() after the function is defined. In addition to the solutions in comments and the other answer, another option would be to put the script in a separate file and invoke it with defer
.
printFunc.js:
print1();
In the html file:
<script src="printFunc.js" defer></script>
This will invoke print1()
. Note that defer
does not work if the script is not external.
Just for fun (and To see how the browser goes through <script>
tags), you can even invoke the function via setTimeout:
<script>
setTimeout(function(){ print1(); }, 3000);
</script>
<script>
function print1(){
alert("hello");
document.getElementsByTagName("p").innerHTML="hey";
}
</script>