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

0
0
Asked By MellowPine42 On

I have a JavaScript file containing an exported `Message()` function that finds the element with ID `logged_in_message` and changes its text. I tried loading it in `index.html` with ``, but the code only works when written directly inside an inline `` tag. The HTML file is at the project root, while the JavaScript file is in a `src` folder. I'm also using Vue, so I'm wondering whether that affects how the script should be loaded. What is the correct way to include and run this file?

4 Answers

Answered By QuietFalcon7 On

There are a few separate issues here. First, `scr` is a typo—the attribute is `src`. Also make sure the folder name in the path is correct: use `src/main.js` if the folder is actually named `src`. Since the file uses `export`, load it as a module: ``. Finally, declaring `Message()` doesn’t run it, so call `Message()` after the function definition.

MellowPine42 -

Thanks! I changed `scr` to `src` and called the function after declaring it, and it works now.

Answered By BrightOtter19 On

If you don’t need modules, remove `export default` and include the file with a normal script tag. If you do keep the export, `type="module"` is required. In either case, the function must actually be invoked; importing or defining a function alone won’t execute its body.

Answered By SilverMaple31 On

You can verify the path by opening the browser’s developer tools and checking the Network or Console tab. A 404 means the file path is wrong; a module or syntax error usually means `type="module"` is missing. Also note that Vue applications generally load JavaScript through the Vue build tool, so direct script inclusion may not be the normal approach inside a Vue component.

Answered By CedarWave58 On

Make sure the script runs after the HTML element exists. Putting the script just before `` usually handles that, or you can use `defer` for a regular script. With a module script, execution is deferred by default, but the element with `id="logged_in_message"` still needs to be present when `Message()` runs.

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.