Criatura Eterna
Criatura Eterna

Reputation: 283

Can I create a javascript file that works both HTTP and HTTPS

I have not been able to find a correct answer for this one. I have a script, let's call it http://www.example.com/testing.js which I used over several sites that are HTTP served. Now I have two new site that are HTTPS served and when I add the file <script src="http://www.example.com/testing.js"></script> I get the following error

Mixed Content: The page at 'https://location.mysite.com/my-account' was loaded over HTTPS, but requested an insecure script 'http://www.example.com/testing.js'. 

This request has been blocked; the content must be served over HTTPS.

I want to use the same file over HTTPS and HTTP, what do I need to change or add to my javascript to serve both of them?

Upvotes: 2

Views: 2377

Answers (2)

Tom
Tom

Reputation: 4846

You should use:

<script src="https://www.example.com/testing.js"></script>

From an https webpage it will load the https version and from an http webpage it will load the https version too, and it will not be blocked (what is blocked it loading http javascript from an https webpage).

That solution works but is not the best:

<script src="//www.example.com/testing.js"></script>

From an https webpage it will load the https version and from an http webpage it will load the http version.

It's not the best because it's less secure, and it force you to allow http and https on the server hosting the javascript (or get the 301 penalty).

Note that you should think about migrating your http websites to https, it's 2017 now...

Upvotes: 2

Shakti Phartiyal
Shakti Phartiyal

Reputation: 6254

You should call the file like so:

<script src="//www.example.com/testing.js"></script>

It will automatically choose protocol according to the page's protocol. That is the reason there is no protocol in the code I gave.

BUT REMEMBER This will only work if your domain www.example.com can also be served over https:// i.e has SSL support

Upvotes: 7

Related Questions