Created
January 31, 2013 15:37
-
-
Save Craftworks/4683753 to your computer and use it in GitHub Desktop.
jQuery プリロードページャープラグイン(事前読み込み & スクロール監視)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($) { | |
$.preloadPager = function(options) { | |
var settings = $.extend({ | |
autoLoad: true, | |
cache: false, | |
content: '.content', | |
pager: '#pager', | |
margin: $(window).height() | |
}, options); | |
var autoLoad = settings.autoLoad, | |
didScroll = false, | |
nowLoading = false, | |
timer, | |
$content = $(settings.content), | |
$pager = $(settings.pager), | |
nextUrl = $pager.attr('href'), | |
$cache; | |
var remain = function(element) { | |
var $element = $(element), | |
eBottom = $element.offset().top + $element.height(), | |
wBottom = $(document).scrollTop() + $(window).height(); | |
return ( eBottom - settings.margin < wBottom ); | |
} | |
var monitor = function() { | |
if ( !didScroll ) return; | |
didScroll = false; | |
if ( !remain(settings.content) ) return; | |
appendContent(); | |
}; | |
var preload = function() { | |
if ( !nextUrl ) return; | |
nowLoading = true; | |
var onSuccess = function(data) { | |
if ( settings.loadCallback ) { | |
data = settings.loadCallback(data); | |
} | |
var $data = $(data); | |
nextUrl = $data.find(settings.pager).attr('href'); | |
$cache = $data.find(settings.content).children(); | |
nowLoading = false; | |
}; | |
$.ajax({ url: nextUrl, cache: settings.cache, success: onSuccess }); | |
}; | |
var appendContent = function() { | |
if ( settings.appendCallback ) settings.appendCallback(); | |
$content.append($cache); | |
if ( nextUrl ) { | |
preload(); | |
} else { | |
if ( autoLoad ) window.clearInterval(timer); | |
} | |
}; | |
if ( autoLoad ) { | |
$pager.hide(); | |
$(window).scroll(function() { | |
didScroll = true; | |
}); | |
timer = window.setInterval(monitor, 200); | |
} else { | |
$pager.click(appendContent); | |
} | |
preload(); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment