HTTP to HTTPS For images with jQuery or by Leaving protocol

Published



You have a domain in https://www.example.com, and it contains large number of images but image sources are starting from http:// .   Example: http://www.example.com/image.jpg.

Problem you are facing is, When you open your website with https://www.example.com , this will show ssl warning in browser that you are attempting to access non-secure contents from your secure website.

To prevent this problem, there are Three Choices.

  • Manually add "https://" instead of all "http://" in all image sources.

  • Without defining protocol information, http:// or https:// in image source, instead leave the protocol information by just adding "//" instead of "http://" and  "https://"

  • Use a Program that converts all images src to start from https:// instead of http://


In first method, it might take time.

Best solution here is Second Method! that you leave any protocol information.
For example
instead of  <img src='http://www.example.com/image.jpg'/>
Use   <img src='//www.example.com/image.jpg'/>
So it will automatically inherit protocol from website address.The browser will use whatever the current protocol is.
If you are visiting http://www.example.com then image source will also be http://
And if you are visiting https://www.example.com ,thenimage source will also be https://


Third method is something that i wont suggest you to do because it might effect page load time and will be requesting two times to the server for one image object. one for htt and other for https.
even if it is so, it will be good if you know how to do that with a simple jQuery Plugin.
This simple jQuery plugin that replace all http:// in image source to https:// when the document is ready.

insert this script just before your </body> tag.
It needs jQuery to work. So don't be panic trying this without a working jQuery called to your page first.

<script type='text'/JavaScript>
$(document).ready(function() {
  $("img").each(function() {
    var i = $(this).attr("src");
    var n = i.replace("http://", "https://");
    $(this).attr("src", function() {
      return n
    })
  })
});
</script>






Comments

Post a Comment