I just found out about this incredibly useful trick for loading absolute resources with either http: or https: depending on the protocol with which your page was loaded (to avoid those "mixed content" complaints from browsers).
Amazingly, you can just leave the scheme (protocol) part off the URL entirely. So for instance, if you're loading jQuery from the Google CDN with this path:
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'></script>you can load it like this instead:<script src='//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'></script>If the page that's in is served via http, that path will become http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.jsIf it's https, that will become
https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.jsE.g., it's a path relative to the protocol (scheme) but in all other ways absolute.
(Naturally, if you load a file via the file: protocol — e.g., locally — it will try to resolve that locally and blow up. But you don't do that, do you?)
Don't trust it? Neither did I, but I haven't found a browser in which it doesn't work, nor apparently have these guys.
And you thought you knew all there was to know about URIs...
3 comments:
I'm a big fan of leaving off the protocol, yet I've noticed that very few major sites do this. I assume they either don't know or are not confident that all browsers will handle it.
Likewise, I wondered why google-analytics scripts still dynamically append the protocol. It turns out this is needed for some specific IE6 security settings.
And there is a bug in IE7 (and/or 8) such that css files included without protocol are downloaded twice. But for img tags and css urls, I see no reason to include the protocol.
The article explains a simple but useful approach to handling resources across HTTP and HTTPS by omitting the protocol from absolute URLs. This helps avoid mixed-content issues while allowing the browser to use the same protocol as the page. It is a neat technique for developers working with external libraries and CDN resources.
The example using jQuery clearly demonstrates how a protocol-relative URL can adapt automatically depending on how the page is loaded. For developers strengthening their JavaScript fundamentals, Javascript Online Course can be useful for learning more about how web resources and scripts are integrated into applications.
I also like that the article points out the practical limitation with local file: URLs while explaining why the technique works across HTTP and HTTPS. Understanding these small browser and URL behaviors can help developers avoid unexpected resource-loading problems. Javascript Online Training can help learners develop a broader understanding of JavaScript and web development concepts.
Post a Comment