简体   繁体   English

我应该将 Javascript 放在 HTML 文件的头部还是正文中?

[英]Should I Put Javascript in the Head or Body of an HTML File?

I am making a search engine, and I have the code to redirect http to https when users access my page.我正在制作一个搜索引擎,当用户访问我的页面时,我有代码将 http 重定向到 https。
Except I'm not sure if I should put it in the head or body section of my page.除了我不确定是否应该将它放在页面的头部正文部分。
Here's what I've got:这是我所拥有的:

if(window.location.protocol != 'https:') {
  location.href = location.href.replace("http://", "https://");
}


Also I would like to know if the code I have actually works if that's OK.另外我想知道我的代码是否真的有效,如果可以的话。

将它放在文档<head>中的<script>标签中,放在任何其他<script>标签之前,以便在下载页面的所有资源之前执行。

No matter where you put it will work but you would unnecessarily loading too many doms if you put the script tag later and also making the user wait slightly longer best is head.不管你把它放在哪里,它都可以工作,但是如果你稍后放置脚本标签,你会不必要地加载太多的dom,并且让用户等待的时间稍微长一点最好是头。

<head>
<script type="text/javascript">
if(window.location.protocol != 'https:') {
  location.href = location.href.replace("http://", "https://");
}
</script>
</head>

JavaScript in head or body You can place any number of scripts in an HTML document.头部或正文中的JavaScript您可以在 HTML 文档中放置任意数量的脚本。 Scripts can be placed in the body, or in the head section of an HTML page, or in both.脚本可以放在正文中,也可以放在 HTML 页面的 head 部分中,也可以放在两者中。 Keeping all code in one place, is always a good habit.将所有代码放在一个地方,始终是一个好习惯。

<head>
<script language="JavaScript">
if(window.location.protocol != 'https:') {
  location.href = location.href.replace("http://", "https://");
}
</script>
</head>

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

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