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

0
0
Asked By MellowPine42 On

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?

4 Answers

Answered By QuietOrbit91 On

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.

Answered By NimbleOak_28 On

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.

Answered By CrispHarbor7 On

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.

Answered By BlueCedar6 On

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();

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.