Loading jQuery via HTTP or HTTPS depending on the request protocol without document.write
- May 20, 2011
When running a page with HTTPS, you’ll want to also load any external resources such as javascript via HTTPS. A lot of people recommend loading jQuery from the Google CDN via the following javascript script:
<script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://" : "http://"); document.write(unescape("%3Cscript src='" + gaJsHost + "ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js' type='text/javascript'%3E%3C/script%3E")); document.write(unescape("%3Cscript src='" + gaJsHost + "ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js' type='text/javascript'%3E%3C/script%3E")); document.write(unescape("%3Cscript src='" + gaJsHost + "ajax.googleapis.com/ajax/libs/swfobject/2.1/swfobject.js' type='text/javascript'%3E%3C/script%3E")); </script>
This works just fine, however you can let the browser select the protocol depending on the request by the following snippet:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/swfobject/2.1/swfobject.js"></script>
This is obviously much cleaner, and you can see the full URL rather than javascript code to build up a string. The key here is the double slash within the src attribute. This kind of url works for any web resource and is particularly useful for loading resources from the Google CDN.