jQuery AJAX Code Abuse
This code snippet doesn't quite qualify as a Weecode at 150 characters, but it's a great demonstration of what can be done with a bit of jQuery and a blatant disregard for programming technique. This is a jQuery extension that enables AJAX content loading, with caching, on a valid link selector:
$.fn.cc=function(t){$(this).click(function(){
return!((d=(o=$(this)).data(h=this.href))?$(t).html(d):$.get(h,function(d){o.data(h,d);$(t).html(d)}))})
}
If you prefer a more - ahem - readable version:
$.fn.cc = function(t) {
$(this).click(function(){
return!(
(d=(o=$(this)).data(h=this.href))
?$(t).html(d)
:$.get(h,function(d){o.data(h,d);$(t).html(d)})
)
})
}
For example, the following code will tell links with the class "load" to insert the content at their URL into the div with the id "ajax-content":
$('a.load').cc('#ajax-content');
The first time the URL is requested the content will be loaded into the div. Subsequent calls will be loaded instantly, forgoing the unneeded HTTP request. This is particularly useful for pagination.
"But browsers can cache requests internally" you say. Well, yes, and no. Caching behaviour is unpredictable, and anyway, you're missing the point.
For the sake of completeness, a jQuery extension should handle library conflicts, the possibility that it will be auto-magically appended to other scripts, allow for chaining, and support failed AJAX requests:
;(function($){
$.fn.cc = function(t) {
return $(this).click(function(){
return!(
(d=(o=$(this)).data(h=this.href))
?$(t).html(d)
:$.get(h,function(d,s){
if(s=="success")
o.data(h,d) && $(t).html(d)
else
window.location=h
})
)
})
}
}(jQuery));
As an added bonus, you can cache requests before the user even clicks on the link. I like to pre-cache the 'next' link within pagination areas.
$.fn.precache = function() {
return $(this).each(function() {
o=$(this);h=this.href;
$.get(h,function(d,s){
if(s=="success") o.data(h,d);
});
});
}
Pre-cache content by:
$('.next').precache();
Or, for a much more readable version: use this file.