lazy load fix for swup

This commit is contained in:
cupcakearmy 2019-10-06 15:40:27 +02:00
parent 5d708919b6
commit c57c14b3c8
3 changed files with 20 additions and 18 deletions

View File

@ -24,18 +24,17 @@ add_action( 'wp_enqueue_scripts', function () {
function lazy_load_ajax_handler() { function lazy_load_ajax_handler() {
$args = json_decode( stripslashes( $_POST['query'] ), true ); query_posts( [
$args['paged'] = $_POST['page'] + 1; 'post_status' => 'publish',
$args['post_status'] = 'publish'; 'paged' => $_POST['page'] + 1,
query_posts( $args ); 'name' => $_POST['name'],
] );
if ( have_posts() ) { while ( have_posts() ) {
while ( have_posts() ) { the_post();
the_post(); get_template_part( 'post-preview', get_post_format() );
get_template_part( 'post-preview', get_post_format() );
}
} }
die; wp_die();
} }
add_action( 'wp_ajax_lazy_load', 'lazy_load_ajax_handler' ); add_action( 'wp_ajax_lazy_load', 'lazy_load_ajax_handler' );

View File

@ -11,10 +11,9 @@
<script> <script>
const WPParams = { const WPParams = {
lazy: JSON.parse(`<?= json_encode( array( lazy: JSON.parse(`<?= json_encode( array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX 'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php',
'posts' => $wp_query->query_vars, // everything about your loop is here
'current_page' => get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1, 'current_page' => get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1,
'max_page' => $wp_query->max_num_pages 'max_page' => $wp_query->max_num_pages,
) ) ?>`) ) ) ?>`)
} }
</script> </script>

View File

@ -4,6 +4,7 @@ export default () => {
const bottomOffset = 300 const bottomOffset = 300
const app = document.getElementById('app') const app = document.getElementById('app')
let loading = false let loading = false
let page = WPParams.lazy.current_page
function load() { function load() {
@ -11,18 +12,21 @@ export default () => {
if (!loading && pixelToBottom < bottomOffset) { if (!loading && pixelToBottom < bottomOffset) {
loading = true loading = true
$.ajax({ $.ajax({
url: WPParams.lazy.ajaxurl, url: WPParams.lazy.ajaxurl,
data: { data: {
'action': 'lazy_load', name: window.location.pathname
'query': JSON.stringify(WPParams.lazy.posts), .replace(/(\/\d+){3}\//, '')
'page': WPParams.lazy.current_page .replace(/\/$/, ''),
action: 'lazy_load',
page,
}, },
type: 'POST', type: 'POST',
success: function (data) { success: (data) => {
if (data) { if (data) {
$('#list').find('hr:last-of-type').after(data) // where to insert posts $('#list').find('hr:last-of-type').after(data) // where to insert posts
WPParams.lazy.current_page++ page++
loading = false loading = false
} }
} }