Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Webdev beginner mistake – using javascript function in html?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

You should set the script type to module and import the function from index.js.

<script type="module">
import { myJavascriptFunc } from './index.js';
myJavascriptFunc();
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading