Friday, June 21, 2013

Use protocol less URL for referencing jQuery

Learnt something new today and thought of sharing. Most of us, include the reference of jQuery library (if Google CDN is used) like this,
http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
As you can see it is using HTTP protocol. The advantage of Google CDN files are cached up to one year which means that your users may not need to download jQuery at all. But when you move from HTTP to HTTPS pages, then you need to make sure that you are using https protocol for referencing jQuery as pages served via SSL should contain no references to content served through unencrypted connections.

Related Post:
And take a note that content served via SSL are not cacheable. Browsers will simply ignore content served over SSL for caching. So you need to make sure that if you are moving from HTTP to HTTPS url, use correct protocol for referencing jQuery library as well.

The better approach would be to use "protocol-less" URL.
//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
It looks strange and initially I also felt the same but "protocol-less" URL is the best way to reference third party content that’s available via both HTTP and HTTPS. When a URL’s protocol is omitted, the browser uses the underlying document’s protocol instead.

Thus, using the protocol-less URL allows a single script reference to adapt itself to what’s most optimal: HTTP and it’s full caching support on HTTP pages, and HTTPS on secured pages so that your users aren't confronted with a mixed content warning.

Must Read:
Feel free to contact me for any help related to jQuery, I will gladly help you.