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() {
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1;
$args['post_status'] = 'publish';
query_posts( $args );
query_posts( [
'post_status' => 'publish',
'paged' => $_POST['page'] + 1,
'name' => $_POST['name'],
] );
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
get_template_part( 'post-preview', get_post_format() );
}
while ( have_posts() ) {
the_post();
get_template_part( 'post-preview', get_post_format() );
}
die;
wp_die();
}
add_action( 'wp_ajax_lazy_load', 'lazy_load_ajax_handler' );

View File

@ -11,10 +11,9 @@
<script>
const WPParams = {
lazy: JSON.parse(`<?= json_encode( array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => $wp_query->query_vars, // everything about your loop is here
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php',
'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>

View File

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