简体   繁体   中英

Script is before /body but it runs before page is loaded

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.

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.

You can't be blamed for coming to that conclusion, but it's actually not the case.

alert() 's are processed by the operating system asynchronously from the JavaScript that spawned them and can usually be rendered faster than the JavaScript can execute. Additionally, an alert() is a "blocking" API call, it freezes the UI so that rendering doesn't sync up with processing.

Instead of an alert() use a console.log() . You will find that doing so shows that your code is running when it should.

Here's an example of how an alert() can mislead your interpretation of the flow of a sequence.

 console.clear(); console.log("test before alert()"); alert("Look at the console. Notice how you don't see the log message that came before me?\\nEven though the JavaScript received the instruction to write to the console, the OS can render an alert() faster than that."); 

Here's the same concept again, but this time without offloading any work to the OS:

 console.clear(); console.log("test before console.log()"); console.log("Look at the console. Notice how you now do see the log message that came before me?"); 

Having your script at the end of the body is an outdated pattern. You should prefer to load the script in the head with the defer attribute (read more https://mdn.io/script ). If you can't do that, in your script you may use a load listener to delay execution until all loading is complete.

window.addEventListener('load', () => {console.log('tada!')});

It takes time for the browser to parse your HTML and build the DOM, and your script will start running as soon as it is encountered, so basically you're setting up a race and hoping the js interpreter loses. Not a reliable way to run asynchronous code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM