Alert () script appears before loading the site content (although I added a tag at the bottom of the html file)

I'm just starting out with JavaScript, and I am following this online course where it states that if I insert tags <script>at the bottom of the page just before the closing tag <body>, I should be able to see the website is being rendered first and then the JavaScript code, but on in fact, it is executed in a different way, JavaScript code is executed first, and only after I click "OK" in the message that appears, I can fully see the website rendered.

Here is the code

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

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

, , . alert(); ? , - ? ( Chrome). , , , .

+4
1

- :

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

window.onload = fun... : ", ". , ( , , ..), .

- :

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

async " script ", defer " ".

0

Source: https://habr.com/ru/post/1669497/


All Articles