简体   繁体   中英

Loading javascript dynamically based on the http or https protocol

I have a javascript file located in a different server, and I am including the javascript file over http page like

<script type="text/javascript" src="http://www.example.com/scriptfile.js">

or over https page like

<script type="text/javascript" src="https://www.example.com/scriptfile.js">

The problem is, that I have page switching from http to https , for example, if a user is in

http://www.example.com/home (site home URL) and I load the javascript over http , now when the user navigates to another page like https://www.example.com/transaction (site transaction URL), I load the script over https and its working fine. From the mentioned transaction URL if the user hits the https://www.example.com/home (home URL changed to https ), the script which I loaded over http fails because of unsecured content. Any suggestion to handle this is welcomed.

The protocol is optional. If you omit it, the browser will use whatever the document's protocol is. So you can do:

<script type="text/javascript" src="//www.mydomain.com/scriptfile.js">

The correct protocol will be used.

Use a protocol-relative URL for your script:

<script type="text/javascript" src="//www.mydomain.com/scriptfile.js">

This will use the same protocol as the calling page.

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