HTML File(firstHTML.html)
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p id="demo">First Paragraph</p>
<p id="demo2">Second Paragraph should be something different</p>
<script src="myScript.js">
show3();
</script>
</body>
</html>
JavaScript File(myScript.js)
let show3 = function() {
document.getElementById(‘demo2′).innerHTML=’I am trying to change the second paragraph using an anonymous function in an external JS file’;
};
I was expecting for the show() function to run since it’s below the
tag. I am still learning about javascript scope so it’s entirely possible that anonymous functions don’t have a global scale and so my function won’t run but why is my question. Thank you all in advance.
4
Answers
The issue was caused by calling show3() before the external JavaScript file had been loaded and parsed.
think of it like this.
when you put src attribut to script tag
all the content in the script tag will be replaced with code in source file.
example:
❌ wrong way
script.js
inside index.html
✅ rights way
index.html
or call show() function inside script.js also
script.js
Excellent query! The problem is that until the external JavaScript file is fully loaded, any inline code, such as show3(), will not be executed by the element with the src attribute. You can utilize the window.onload event in your external JS file or call the function after the external script has completed loading to make sure it executes. You will quickly understand JavaScript scope if you continue to explore!
Answer : Yes
explanation
when you use the
src
with thescript
tag its actually import javaScript you write in the file inside the script tag.