The solution to the failure of HTML introducing external JS

Problem Description:

JavaScript files are imported from outside the script tag, but it does not work, and the JS code is invalid

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>Login</title>
		<script src="js/main.js" type="text/javascript"></script>
	</head>
	
	<body>
		<form action="XXXXXX" method="post" name="login">
			Username: <input type="text" name="username" id="username" /> <br>
			Password: <input type="password" name="password" id="password" /> <br>
			<input type="submit" name="login" id="login" value="登录"/>
			<input type="button" name="logon" id="logon" value="注册" />
		</form>
	</body>
</html>

Cause analysis:

The execution order of HTML code is from top to bottom. The browser parses the HTML code from top to bottom. If JS is introduced into the head, the page tag may not be loaded during JS execution, resulting in the failure of JS to find the action object

Solution:

Just import an external JS file after the body

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>Login</title>
	</head>
	
	<body>
		<form action="http://42.192.60.64:8080/user" method="post" name="login">
			Username: <input type="text" name="username" id="username" /> <br>
			Password: <input type="password" name="password" id="password" /> <br>
			<input type="submit" name="login" id="login" value="登录"/>
			<input type="button" name="logon" id="logon" value="注册" />
		</form>
	</body>
	
	<script src="js/main.js" type="text/javascript"></script>
</html>

Read More: