脚本在 /body 之前,但它在页面加载之前运行

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

我是网络开发的新手,我正在尝试 node.js 使用 express。

我的目录结构如下:

第一个应用程序
----node_modules
----public
--------脚本
--------------additems.js
----观看次数
--------home.ejs
----app.js

粗体是文件夹,斜体是文件。

这是文件 additem.js:

console.log("js connected");
alert("test");

这是 home.ejs 文件:

<!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>

这是 app.js 文件:

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");

 })

页面加载前javascript被运行的问题

我知道这一点,因为警报消息先于其他任何内容出现。此外,我尝试使用一些 DOM 元素,但它们已返回为未定义。

在网上搜索我可以看到我的脚本位置在标记之前是正确的,并且应该是 运行 最后。

我在这里错过了什么?

我知道使用 onload 事件的可能性,但我想避免它,除非它是必须的,此外 我想了解为什么脚本不是 运行最后就像它应该做的那样。

更新 - 已解决

感谢 Scott Marcus 的贡献,帮助我解决了问题。

其实是双重错误

1- 我使用了 alert() 并且这不是你提到的提示。
2-我没有在 alert() 之后提到代码,因为我是从一个受信任的网站复制的,我希望问题尽可能简短。但是,代码有一个错误,导致它无法以正确的方式成为 运行。

谢谢大家

将脚本放在正文末尾是一种过时的模式。您应该更喜欢使用 defer 属性在 head 中加载脚本(阅读更多内容 https://mdn.io/script)。如果您不能这样做,您可以在脚本中使用加载侦听器来延迟执行,直到所有加载完成。

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

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.

得出这样的结论不能怪你,但事实并非如此

alert() 由操作系统从生成它们的 JavaScript 异步处理,通常可以比 JavaScript 执行更快地呈现。此外,alert() 是一个 "blocking" API 调用,它会冻结 UI,因此渲染不会与处理同步。

使用 console.log() 而不是 alert()。你会发现这样做表明你的代码在它应该的时候是 运行 。

这是一个 alert() 如何误导您对序列流的解释的示例。

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.");

这里又是相同的概念,但这次没有将任何工作卸载到 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?");

浏览器解析你的 HTML 并构建 DOM 需要时间,你的脚本会在遇到它时立即启动 运行ning,所以基本上你'重新设置比赛并希望 js 解释器失败。不是 运行 异步代码的可靠方法。