-2

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

我有以下目录结构:

第一个 App
---- node_modules
---- public
-------- scripts
------------ additems.js
---- views
-------- 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() 之后提及代码,因为我从受信任的网站复制了它,我希望问题尽可能简短。但是,代码有一个错误,导致它无法以正确的方式运行。

谢谢大家。

4

3 回答 3

2

在页面加载之前运行javascript的问题

我知道这一点,因为警报消息出现在其他任何内容之前。

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

alert()'s 由操作系统与生成它们的 JavaScript 异步处理,并且通常可以比 JavaScript 执行得更快。此外,analert()是一个“阻塞”API 调用,它会冻结 UI,因此渲染不会与处理同步。

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

这是一个如何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.");

这又是相同的概念,但这次没有将任何工作卸载到操作系统:

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

于 2018-03-08T01:53:53.243 回答
0

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

window.addEventListener('load', () => {console.log('tada!')});
于 2018-03-08T01:53:37.490 回答
0

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

于 2018-03-08T02:02:45.900 回答