Skip to content

Instantly share code, notes, and snippets.

@aarongustafson
Forked from scottjehl/anchorinclude.js
Created October 3, 2011 14:13
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarongustafson/b976b67e88ffbfc9f125 to your computer and use it in GitHub Desktop.
Save aarongustafson/b976b67e88ffbfc9f125 to your computer and use it in GitHub Desktop.
Anchor-include Pattern
/*
* anchor-include pattern for already-functional links that work as a client-side include
* Copyright 2011, Scott Jehl, scottjehl.com
* Dual licensed under the MIT
* Idea from Scott Gonzalez
* to use, place attributes on an already-functional anchor pointing to content
* that should either replace, or insert before or after that anchor
* after the page has loaded
* Replace: <a href="..." data-replace="articles/latest/fragment">Latest Articles</a>
* Before: <a href="..." data-before="articles/latest/fragment">Latest Articles</a>
* After: <a href="..." data-after="articles/latest/fragment">Latest Articles</a>
* On domready, you can use it like this:
$("[data-append],[data-replace],[data-after],[data-before]").ajaxInclude();
*/
(function( $ ){
if ( $.fn.jquery.replace(/\./g,'') < 143 )
{
throw new Error('jQuery 1.4.3 or higher is required');
return;
}
$.fn.ajaxInclude = function()
{
return this.each(function(){
var $el = $( this ),
target = $el.data( 'target' ),
$targetEl = target && $( target ) || $el,
methods = [ 'append', 'replace', 'before', 'after' ],
ml = methods.length,
method,
url;
while ( ml-- )
{
method = methods[ ml ];
if ( $el.is( '[data-' + method + ']' ) )
{
url = $el.data( method );
break;
}
}
if ( method == 'replace' )
{
method += 'With';
}
if ( url && method )
{
$.get( url, function( data ){
$el.trigger( 'ajaxInclude', [$targetEl, data] );
$targetEl[ method ]( data );
});
}
});
};
})( jQuery );
(function(a){if(a.fn.jquery.replace(/\./g,"")<143){throw new Error("jQuery 1.4.3 or higher is required");return}a.fn.ajaxInclude=function(){return this.each(function(){var d=a(this),f=d.data("target"),e=f&&a(f)||d,b=["append","replace","before","after"],h=b.length,g,c;while(h--){g=b[h];if(d.is("[data-"+g+"]")){c=d.data(g);break}}if(g=="replace"){g+="With"}if(c&&g){a.get(c,function(i){d.trigger("ajaxInclude",[e,i]);e[g](i)})}})}})(jQuery);
@aarongustafson
Copy link
Author

You got it. Here’s the actual line in the HTML of that article:

<a id="comment-loader" data-replace="/comments/from-mobile-friendly-to-mobile-first/" href="/archives/2011/10/12/from-mobile-friendly-to-mobile-first/comments/#comments">View comments on this entry and add your own</a>

Good call on the canonical URL. That hadn’t occurred to me.

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