Problems running imported JS in EJS file

Issue

I made an express Nodejs server and set the static folder.
The CSS has access to the page, but the JS does not find any elements. Everything is NULL.

app.use(express.static(__dirname + '/static'))

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

//test from clientside index.js
document.body.append('test')
<script src="js/index.js"></script>
<link rel="stylesheet" href="style/main.css">

What am I doing wrong?

Solution

Problem

DOM doesn’t load yet when your JS runs. It’s not related to EJS, that’s just how every script works.

Solution

Add defer attribute

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

Answered By – Konrad Linkowski

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published