如何在需要时通过HTTPS包含CSS和JS文件?

我将一个外部CSS文件和一个外部JS文件添加到我的页眉和页脚。 当加载HTTPS页面时,一些浏览器抱怨我正在加载不安全的内容。

当页面本身是HTTPS时,是否有一种简单的方法可以使浏览器通过HTTPS加载外部内容?

使用协议相对path。

因此不是

<link rel="stylesheet" href="http://example.com/style.css"> <script src="http://example.com/script.js"></script> 

但是如此

 <link rel="stylesheet" href="//example.com/style.css"> <script src="//example.com/script.js"></script> 

那么它将使用父页面的协议。

Nute&James Westgate在对后面的答案进行评论时是正确的。

如果我们看看行业级别的外挂javascript包含,成功的使用document.location.protocol嗅探和脚本元素注入tu使用适当的协议。

所以你可以使用像这样的东西:

 <script type="text/javascript"> var protocol = ( ("https:" == document.location.protocol) ? "https" : "http" ); document.write( unescape( "%3Cscript" + " src='" + protocol + "://" + "your.domain.tld" + "/your/script.js" + "'" + " type='text/javascript' + "%3E" + "%3C/script%3E" ) // this HAS to be escaped, otherwise it would // close the actual (not injected) <script> element ); </script> 

包括外部CSS也可以做同样的事情。

顺便说一句:要小心只在你的CSS中使用相对的url()path,否则,你仍然可以得到“混合安全和不安全”警告..​​..

如果使用相对path(并且内容位于相同的域),则内容应该使用请求页面的任何协议。

但是,如果要通过域到CDN或资源站点,或者如果您需要使用绝对path,则需要使用服务器端脚本来更改链接,或者始终使用https://

与逃脱的响应(这也将起作用)相反,您可以跳过该部分并使用正确的方法将节点添加到您的dom树中:

 <script type="text/javascript" language="javascript"> var fileref=document.createElement('script'); fileref.setAttribute("type","text/javascript"); fileref.setAttribute("src", document.location.protocol + '//www.mydomain.com/script.js'); document.getElementsByTagName("head")[0].appendChild(fileref); </script> 

但是,协议相对path将是一条路。