Pre-fetching has been around for some time now and is often used to load images and CSS files. While your mileage may vary, you can also pre-fetch your CDN calls (e.g. Jquery) and make your apps a bit faster by loading scripts in the <head> section to load JS calls before your <script> get resolved by browsers.
You can also CDN outage proof it (when it rarely happens) by having local JS libraries (for rainy days) using some quick jquery checks (based on code from +Testing
Without pre-fetch:
Code Snippet
- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
- <script>
- if (typeof jQuery == 'undefined') {
- document.write(unescape("%3Cscript src='[yourlocalbackupjqueryfile].js' type='text/javascript'%3E%3C/script%3E"));
- }
- var startTime = new Date();
- jQuery.ready();
- var endTime = new Date();
- var difference = endTime - startTime;
- alert("With out prefetch: " + difference + " milliseconds");
- </script>
Result:
With Pre-fetch:
Code Snippet
- <link rel="dns-prefetch" href="//ajax.googleapis.com" />
- <link rel="dns-prefetch" href="//ajax.googleapis.com" />
- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
- <script>
- if (typeof jQuery == 'undefined') {
- document.write(unescape("%3Cscript src='[yourlocalbackupjqueryfile].js' type='text/javascript'%3E%3C/script%3E"));
- }
- var startTime = new Date();
- jQuery.ready();
- var endTime = new Date();
- var difference = endTime - startTime;
- alert("With prefetch: " + difference + " milliseconds");
- </script>
Result:
saved about 1 millisecond!
Comments