![](/img/trans.png)
[英]is there a difference between putting a javascript in the head or in the body?
[英]difference between putting scripts in body or outside body
我现在有这个结构:
<!DOCTYPE html>
<html>
<head>
<!-- stylesheets-->
<link rel='stylesheet' href='/static/stylesheets/style.css'/>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,600,300' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<link href="/static/css/bootstrap/bootstrap-notify.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="/static/css/portal/simple-sidebar.css" media="screen" />
<link rel="stylesheet" type="text/css" href="/static/css/userProfileView/user-profile.css" media="screen" />
</head>
<body>
<main>
<div name="main-div" id="main-div-id"></div>
</main>
</body>
<% if(env == 'development') {%>
<script data-main="/static/app/js/main" src="/static/vendor/require.js"></script>
<% } else { %>
<script src="/static/app/optimized/optimized.js"></script>
<% } %>
</html>
如您所见,我的JavaScript位于“底部”,但它们位于body标记之外,而不位于内部。
我确定这会有所作为,但是我不确定将脚本放在<head>
之外和<body>
标记之外有什么不同。
起初我以为我记得<head>
和<body>
是可选的,因此可以将<script>
放在<html>
,但这只是部分正确。
<script>
<html>
内不允许使用<script>
,因为<html>
只能包含<head>
和<body>
。
但是,如果不声明<body>
或<head>
,浏览器将为您隐式创建它们( 在适当的条件下 )。 即这是无效的:
<html>
<head></head>
<body><body>
<script>console.log('test')</script>
</html>
这是隐式创建一个body元素,脚本标签是其中的一部分:
<html>
<head></head>
<script>console.log('test')</script>
</html>
这将隐式创建一个head元素,该脚本标签是以下元素的一部分:
<html>
<script>console.log('test')</script>
</html>
所以不,您永远不要在</body>
之后放置<script>
</body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.