2

When I load the page, the

What is up

shows up, but the "Hello World" from the script.js doesn't. Any help?

The directory looks like this

project
 |
 +-- node modules
 |    
 +-- javascript
 |  |  
 |  +-- script.js
 |    
 +-- views
 |  |  
 |  |  +-- index.ejs
 |    
 +-- server.js
 |
 +-- package.json

index.ejs file

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>Index</title>
  <meta name="description" content="Index">

</head>

<body>
  
  <h1>What is up?</h1>

  <div id = "container">
    
  </div>

</body>

<script src = "javascript/script.js">
    
// var container = document.getElementById("container");
// var content = document.createTextNode("Hello, World!");
// container.appendChild(content);

</script>
</html>

The commented out code in the script is exactly whats included in the script.js file. If I uncomment it, and have the code running in the ejs file, it works. Just not if in the external script.js

server.js file

const express = require('express')
const app = express()

app.set('view-engine', 'ejs')

app.use(express.static('project/javascript'))

app.get('/', (req, res) => {
    res.render('index.ejs')
})

app.listen(3000)
3
  • Try to place the script tag inside the body (before the body's closing tag) Commented Oct 15, 2020 at 6:53
  • Why is that important? Commented Oct 15, 2020 at 10:16
  • Because you can be more confident that all HTML elements are loaded at that point. Since your are using the <div id="container">. Even better would be to listen for DOMContentLoaded. Commented Oct 15, 2020 at 10:31

1 Answer 1

2

If you change the src-attribute to an absolute path, this should work fine:

<script src="/script.js"></script>

Note that I've removed the /javascript subfolder from the url since this is not correct. Also you should pass the subfolder to express.static, i.e.:

app.use(express.static('javascript'));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.