1

Description:

i am new to trying these codes. a Javascript Hello World try. only Line: 6, 22,23,24 (the "script" tags) are important. I refer to another js file 'a1.js' All contents in a1.js is only one line: "alert(1)".

Question is:

i click open the html file in chrome(ver 78.0.3904.108), and the RESULT confuse me: it's popup '1', and then popup '3', and show the words Hello World in the browser.

why I don't see alert(2) pop up?

Can i put javacript in script tagS anywhere in html head and html body and in that order loaded?

<!doctype html>
<html lang="en">
  <head>
  
    <!-- THIS IS THE WIERD PART I -->
    <script src="a1.js"/>
    
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <title>Hello, world!</title>
    
  </head>
  <body>
  
    <!-- THIS IS THE WIERD PART, MAYNE SOMETHING WRONG  -->
    <script>alert(2)</script>
    <h1>Hello, world!</h1>
    <script>alert(3)</script>

    
    <!-- NOTHING SPECIAL IN THIS PART -->    
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
    
    <!-- END --> 
  </body>
</html>
T.Ted
  • 33
  • 3

2 Answers2

4

<script> is not a self-closing tag. You need to change this line:

<script src="a1.js"/>

to this:

<script src="a1.js"></script>

In your <head>

Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
3

The issue just comes from the first script tag, namely if you replace:

<script src="a1.js"/>

with

<script src="a1.js"></script>

then you should observe a normal behavior.

This may sound a bit strange at first sight (because the first syntax is well-formed from an XML point of view), but <script> is not a self-closing tag in HTML, see e.g. that other StackOverflow answer: Why don't self-closing script elements work?; and that blog article gives more details on so-called void tags.

ErikMD
  • 13,377
  • 3
  • 35
  • 71