javascript http to https redirect

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

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> 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!