I'm trying to learn the first steps of web development with plain html and javascript. I feel like I'm missing something completely fundamental. I have two files in a directory that is being served up with python's built-in basic webserver: python -m http.server
.
My browser throws this error when loading the webpage: Uncaught ReferenceError: myJavascriptFunc is not defined
.
Here are my two files.
index.html
<!DOCTYPE html>
<html>
<head>
<script type="module" src="./index.js"></script>
</head>
<body>
<p>Hello!</p>
<script>
myJavascriptFunc();
</script>
</body>
</html>
index.js
export function myJavascriptFunc() {
console.log("inside myJavascriptFunc");
}
I thought that since I declared my javascript file as module in the head section that it would get loaded before the body element was processed...so it should be defined. I've also made sure to export the myJavascriptFunc
function from the script file. What basic mistake did I make?
Edit:
Based on Unmitigated's answer I edited the index.html
file as follows and everything works as expected.
<!DOCTYPE html>
<html>
<head>
<!-- The script element here was removed. -->
</head>
<body>
<p>Hello!</p>
<script type="module">
// This script tag has had the src attribute removed.
import { myJavascriptFunc } from './index.js';
myJavascriptFunc();
</script>
</body>
</html>
Edit 2: To those suggesting that How do I include a JavaScript file in another JavaScript file? is a duplicate, I really don't see how they're related but that could be my inexperience in webdev. That question focuses on loading javascript inside other javascript files. This question is about loading a single javascript file into html. What makes this a duplicate?