简体   繁体   English

alert()脚本在网站内容加载之前弹出(即使我在html文件的底部插入了标签)

[英]alert() script popping up before website's content loads (even though I inserted tag at bottom of html file)

I'm just starting on JavaScript and I'm following along this online course where it claims that if I insert <script> tags at the bottom of the page just before the <body> closing tag I should be able to see the website render first followed by the JavaScript code, but it is actually executing the other way around, the JavaScript code executes first and it's not until after I click "OK" on the message popping up that I'm able to see the website fully rendered. 我刚开始使用JavaScript,我正在关注这个在线课程,声称如果我在<body>结束标记之前在页面底部插入<script>标签,我应该能够看到网站渲染首先是JavaScript代码,但它实际上是以相反的方式执行,JavaScript代码首先执行,直到我在弹出的消息上单击“确定”,我才能看到网站完全呈现。

Here is the code 这是代码

index.html 的index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="css/main.css">
  <title>JavaScript Basics</title>
 </head>
<body>
  <div class="container">
  <h1>Where to place your JavaScript code.</h1>
  </div>
  <script src="scripts.js"></script>
</body>
</html>

scripts.js scripts.js中

alert("This text should appear after page is fully rendered");

I honestly don't know if this is how the code is supposed to work. 老实说,我不知道这是代码应该如何工作。 Do alert(); alert(); scripts always execute first? 脚本总是先执行? Maybe the browser has something to do with it? 也许浏览器与它有关? (I'm using the latest version of Chrome). (我正在使用最新版本的Chrome)。 Anyhow, a well explained answer of what's happening would be much appreciated. 无论如何,对于正在发生的事情的一个很好解释的答案将非常感激。

Personally, I would do something more like: 就个人而言,我会做更多的事情:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="css/main.css">
  <title>JavaScript Basics</title>
 </head>
<body>
  <div class="container">
  <h1>Where to place your JavaScript code.</h1>
  </div>
  <script>
  window.onload = function() {
      alert('This should now load after the page.');
  }
  </script>
</body>
</html>

The window.onload = fun... says "wait until the page has finished loading". window.onload = fun...说“等到页面加载完毕”。 Depending on what the browsers decide to (with images, layout, plugins etc.), this may or may not work for you. 根据浏览器的决定(图像,布局,插件等),这可能适用于您,也可能不适用。

Or even something like: 甚至是:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="css/main.css">
  <title>JavaScript Basics</title>
 </head>
<body>
  <div class="container">
  <h1>Where to place your JavaScript code.</h1>
  </div>
  <script async defer src="scripts.js"></script>
</body>
</html>

With this example, the async attribute means "grab this script file in the background" and the defer means "wait until the page has loaded to execute it". 在这个例子中, async属性意味着“在后台获取此脚本文件”, defer意味着“等到页面加载后执行它”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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