Reading about prefetch and prerender, and especially Chromes prerender, got me thinking that this could to some extent be automated.
My blog has become increasingly slow and I though that this would work as a simple quick-fix.
This script relies on jQuery.
Prefetch
At startup (document ready) it will find any a-links tagged as “prefetch” and add their URL’s to the header prefetch. This will make browsers download and cache the HTML-page (but not the CSS/JS/imagers inside it) you have linked to.
Understand that if you tag a link with this then the browser will download this link – without triggering a JavaScript. This means that you should not tag submit-links like “Save”, “Delete” or similar with “prefetch” or “prerender”.
Example:
1 2 |
<a href="http://site.com" prefetch>Link</a> <a prefetch="http://site.com" onclick="someScript()">Link</a> |
Prerender
Any time a user hovers the mouse over a link this link is put into the headers “prerender”. There can only be one link in the prerender.
The theory here is that the user will usually spend at least 200 milliseconds or more before clicking the link, giving the browser time to download (and cache) the page and all its content. Some browsers (at least Chrome) will even render the whole page in a hidden window and just swap it in when the link is clicked.
The script
Note the lines I have commented out. With these two lines commented out the script works on all “<a href>” links. If you remove the comment on these two then they require the link to be tagged with “prerender”. If prerender has no data then href is used.
Example:
1 2 |
<a href="http://site.com" prerender>Link</a> <a prerender="http://site.com" onclick="someScript()">Link</a> |
And here is the script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<script> /* Prefetch and prerender script by Tedd */ jQuery(document).ready(function () { var links = jQuery('a[prefetch]'); links.each(function () { var link = jQuery(this); var prefetch = link.attr('prefetch'); if (!prefetch) prefetch = link.attr('href'); console.log("Adding prefetch to header: " + prefetch); jQuery('head').append(jQuery('<link />').attr('rel', 'prefetch').attr('href', prefetch)); }); }); jQuery(document).on("mouseenter", "a", function () { var link = jQuery(this); var prerender = link.attr('prerender'); /* Comment out these two lines if you want script to work on all links */ /*if (typeof prerender === typeof undefined) return; */ if (!prerender) prerender = link.attr('href'); console.log("Adding prerender to header: " + prerender); jQuery('head link[rel="prerender"]').remove(); jQuery('head').append(jQuery('<link />').attr('rel', 'prerender').attr('href', prerender)); }); </script> |