(function () { 'use strict'; function initialize(loader) { var grid = loader.parentElement ? loader.parentElement.querySelector('.blog-grid') : null; var sentinel = loader.querySelector('.blog-grid-lazy-load__sentinel'); var status = loader.querySelector('.blog-grid-lazy-load__status'); var loading = false; if (!grid || !sentinel || !window.IntersectionObserver) { return; } var observer = new IntersectionObserver(function (entries) { if (!entries.some(function (entry) { return entry.isIntersecting; }) || loading) { return; } var nextUrl = loader.getAttribute('data-next-url'); if (!nextUrl) { observer.disconnect(); loader.remove(); return; } loading = true; observer.unobserve(sentinel); if (status) { status.textContent = loader.getAttribute('data-loading-text') || ''; } fetch(nextUrl, { credentials: 'same-origin' }) .then(function (response) { if (!response.ok) { throw new Error('Unable to load posts'); } return response.text(); }) .then(function (html) { var documentPage = new DOMParser().parseFromString(html, 'text/html'); var nextGrid = documentPage.querySelector('.blog-grid'); var nextLoader = documentPage.querySelector('[data-kalm-blog-lazy-load]'); if (!nextGrid) { throw new Error('Posts grid not found'); } Array.prototype.forEach.call(nextGrid.children, function (card) { var importedCard = document.importNode(card, true); importedCard.classList.add('blog-card--lazy-reveal'); grid.appendChild(importedCard); }); if (nextLoader && nextLoader.getAttribute('data-next-url')) { loader.setAttribute('data-next-url', nextLoader.getAttribute('data-next-url')); loading = false; if (status) { status.textContent = ''; } observer.observe(sentinel); return; } observer.disconnect(); loader.remove(); }) .catch(function () { observer.disconnect(); loader.remove(); }); }, { rootMargin: '500px 0px' }); observer.observe(sentinel); } document.querySelectorAll('[data-kalm-blog-lazy-load]').forEach(initialize); })();