lazy load remaining posts

This commit is contained in:
cupcakearmy 2019-09-06 22:46:32 +02:00
parent 288de3badc
commit 4d440aefeb
2 changed files with 69 additions and 1 deletions

View File

@ -19,7 +19,7 @@ add_filter( 'wp_headers', function ( $headers ) {
add_action( 'wp_enqueue_scripts', function () {
// JS
wp_enqueue_script( 'liquet-lights', get_template_directory_uri() . '/js/lights.js' );
wp_enqueue_script( 'liquet-main', get_template_directory_uri() . '/js/main.js' );
// CSS
wp_enqueue_style( 'flex', get_template_directory_uri() . '/css/flex.css' );
@ -28,8 +28,39 @@ add_action( 'wp_enqueue_scripts', function () {
wp_enqueue_style( 'liquet-singular', get_template_directory_uri() . '/css/singular.css' );
wp_enqueue_style( 'liquet-logos', get_template_directory_uri() . '/css/logos.css' );
wp_enqueue_style( 'fonts', get_template_directory_uri() . '/vendor/fonts/import.css' );
// Lazy loading
global $wp_query;
wp_register_script( 'lazy_loading', get_template_directory_uri() . '/js/lazy_load.js', array( 'jquery' ) );
wp_localize_script( 'lazy_loading', 'lazy_load_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode( $wp_query->query_vars ), // everything about your loop is here
'current_page' => get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1,
'max_page' => $wp_query->max_num_pages
) );
wp_enqueue_script( 'lazy_loading' );
} );
function lazy_load_ajax_handler() {
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$args['post_status'] = 'publish';
query_posts( $args );
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
get_template_part( 'post-preview', get_post_format() );
}
}
die;
}
add_action( 'wp_ajax_lazy_load', 'lazy_load_ajax_handler' );
add_action( 'wp_ajax_nopriv_lazy_load', 'lazy_load_ajax_handler' );
add_action( 'widgets_init', function () {
register_sidebar( array(

37
liquet/js/lazy_load.js Normal file
View File

@ -0,0 +1,37 @@
jQuery(($) => {
const bottomOffset = 300
const app = document.getElementById('app')
let loading = false
function load() {
const pixelToBottom = this.scrollHeight - (this.scrollTop + this.clientHeight)
if (!loading && pixelToBottom < bottomOffset) {
console.log('Loading...')
loading = true
$.ajax({
url: lazy_load_params.ajaxurl,
data: {
'action': 'lazy_load',
'query': lazy_load_params.posts,
'page': lazy_load_params.current_page
},
type: 'POST',
success: function (data) {
if (data) {
$('#list').find('hr:last-of-type').after(data) // where to insert posts
lazy_load_params.current_page++
loading = false
}
}
})
}
}
// Bind to the scroll event
$('#app').scroll(load)
// Check initial page if they need loading
load.bind(app)()
})