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
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.
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.
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.
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
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically