Skip to content

Instantly share code, notes, and snippets.

@dz0ny
Created December 25, 2011 21:19
Show Gist options
  • Save dz0ny/1519761 to your computer and use it in GitHub Desktop.
Save dz0ny/1519761 to your computer and use it in GitHub Desktop.
Prefetch,prerender, preload HTML5 snippet for jQuery
// create an object named "app" which we can define methods on
var app = {
// returns an array of each url to prefetch
searchUniqueWithLimit: function(selector,limit){
// returns an array for selector
var hrefs = $(selector).map(function(index, domElement){
return $(this).attr("href");
});
// returns the array of hrefs without duplicates
return $.unique(hrefs).slice ( 0, limit?limit:5 );
},
// adds a link tag to the document head for each of prefetchLinks()
addLinkTags: function(selector, type, limit){
// for each searchUniqueWithLimit(jquery selector, seach limit) ...
var self = this;
this.searchUniqueWithLimit(selector,limit).each(function(index,Element){
// check for array and create link element
if ($.isArray( type )) {
$.map(type, function(Type, index){
self.addLinkToHead(Type, Element);
});
}else{
self.addLinkToHead(type, Element);
}
});
},
addLinkToHead: function(type, Element){
console.log($("<link />", {
// with rel=type and href=Element...
rel: type, href: Element
// and append it to the end of the document head
}))
$("<link />", {
// with rel=type and href=Element...
rel: type, href: Element
// and append it to the end of the document head
}).appendTo("head");
}
}
//add five pages for prefetch to head
app.addLinkTags("a.prefetch", "prefetch");
//prefetch google.com
app.addLinkToHead("prefetch", "http://www.google.com");
//prerender first link on page with class prerender
app.addLinkTags("a.prerender", "prerender", 1);
//prerender google.com
app.addLinkToHead("prerender", "http://www.google.com");
//load first three pages in backgroud, with class preload
app.addLinkTags("a.preload", ["prefetch","prerender"], 3);
@Kotpes
Copy link

Kotpes commented Aug 1, 2017

Good work! Exactly what I was looking for

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment