可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
Put it inside a <script>
tag in the <head>
of your document before any other <script>
tags, so that it will execute before downloading all the resources for the page.
回答2:
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>
回答3:
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>