I am new to web developing and I am trying node.js with express.
I have the following directory structure:
First App
----node_modules
----public
--------scripts
------------additems.js
----views
--------home.ejs
----app.js
with bold is a folder and italic is a file.
this is the file additem.js:
console.log("js connected");
alert("test");
and this is home.ejs file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Node</title>
</head>
<body>
<h1>Dynamic Page</h1>
<p></p>
<ol id='olist'>Names List</ol>
<script type="text/javascript" src="../public/scripts/additems.js"></script>
</body>
</html>
And this is the app.js file:
var express = require('express');
var app = express();
console.log("Server has been started!");
//app.use(express.static(__dirname + "/public"));
app.get("/", function(req,res){
//res.send("Home Page");
res.render("home.ejs");
})
The problem that the javascript is being run before the page is loaded
I know this because the alert message is appearing before anything else. In addition I tried to use some DOM elements but they have been returned as undefined.
Searching the net I can see that my script position is correct just before the tag, and supposedly it should run last.
What am I missing here?
I am aware of the possibility of using the onload event, but I want to avoid it unless it is a must, beside I want to learn why the script is not run at last as it supposed to do.
UPDATE - SOLVED
Thanks Scott Marcus for your contribution which helped me solving the problem.
In fact, there was a double error.
1- I used alert() and that is cannot be a hint as you mentioned.
2- I did not mention the code after the alert() because I copied it from a trusted website and I wanted the question to be as short as possible. However, the code had an error that prevented it from being run in the correct way.
Thanks all.
See Question&Answers more detail:
os