Why isn’t my external JavaScript file running in HTML?

August 5, 2026 4 answers
Asked by MellowPine42
I have a JavaScript file containing an exported function: export default function Message() { const messageDisplay = document.getElementById("logged_in_message"); messageDisplay.innerHTML = "Based on your interests"; } In my HTML file, I tried to load it with: Inline JavaScript works, but the code in the external file does not. The JavaScript file is in a src folder, while index.html is in the project root. I'm also using Vue, so I'm wondering whether that affects how the file needs to be loaded. What is the correct way to include and run this file?

Answers

BlueCedar6
Make sure the element with ID `logged_in_message` exists before the function runs. Put the module script near the end of the body, or use `defer` for a regular script. For example: Then in `main.js`: export default function Message() { const messageDisplay = document.getElementById("logged_in_message"); messageDisplay.innerHTML = "Based on your interests"; } Message();
Reply to this answer
CrispHarbor7
There are a few separate issues here. First, the attribute is `src`, not `scr`. Since the file uses `export`, load it as a module: Also, declaring the function does not run it. Call `Message()` after the function definition, or import the function from another module and call it there.
Reply to this answer
NimbleOak_28
If the folder is actually named `scr`, the path must be `scr/main.js`; otherwise rename or use the `src` folder consistently. You can check the browser’s developer tools and Network tab to see whether the file URL returns a 404.
Reply to this answer
QuietOrbit91
If you are not importing the function into another JavaScript module, you do not need `export default` at all. You can define the function normally, include the file with ``, and call it after the page has loaded. With a Vue project, though, it is usually better to let Vue’s build setup handle modules instead of adding scripts directly to the HTML.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions