简体   繁体   中英

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

<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. Scripts can be placed in the body, or in the head section of an HTML page, or in both. 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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