Search code examples
javascripthtmlsslhttpssrc

Have src attributes use same protocol as page


I have a site that uses https in some places, and http in others.

Wasn't a problem until I realized that my scripts with relative paths would always use http. Is it possible to have my relative path src attributes use whichever protocol is used for the page?

Originally I was thinking I could just use location.protocol and location.host, but then realized I'm not actual in javascript when setting the src attributes!

Any ideas?

<script src="/foobar"></script>

Solution

  • Your relative paths will take the protocol and host that the page uses. If this needs to change you could use the BASE tag.

    Also when using absolute paths a double slash will inherit the page's protocol: src="//host.com/path" will be https on an https page and http on an http page.