Last active
January 8, 2024 22:02
-
-
Save khoipro/6e30a956ea8cb45b4c7034c7150100a9 to your computer and use it in GitHub Desktop.
Sample section lazyload using <noscript> - DRAFTING
This file contains hidden or 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
<?php | |
/** Drafting **/ | |
add_filter('the_content', 'codetot_lazyload_home_sections', 1000); | |
function codetot_lazyload_home_sections( $content ) { | |
$front_page_id = get_option('page_on_front'); | |
if ( ! is_page( $front_page_id ) ) { | |
return $content; | |
} | |
if ( ! is_user_logged_in() ) { | |
return $content; | |
} | |
echo '<pre>'; | |
print_r( $content ); | |
echo '</pre>'; | |
$content = str_replace('<section class="section row-san-pham">', '<section class="section row-san-pham lazyload"><noscript>', $content); | |
$content = str_replace('</section>', '</noscript></section><!-- Lazyload section by CODETOT -->', $content); | |
ob_start(); | |
?> | |
<!-- Custom JS to render lazyload sections --> | |
<script> | |
function inViewPort(el) { | |
const rect = el.getBoundingClientRect() | |
const windowHeight = | |
window.innerHeight || document.documentElement.clientHeight | |
const windowWidth = window.innerWidth || document.documentElement.clientWidth | |
const vertInView = rect.top <= windowHeight && rect.top + rect.height >= 0 | |
const horInView = rect.left <= windowWidth && rect.left + rect.width >= 0 | |
return vertInView && horInView; | |
} | |
var sectionEls = Array.property.slice.call(document.querySelectorAll('.section.lazyload')); | |
if (sectionEls && sectionEls.length) { | |
function lazyloadSection( el ) => { | |
if ( ! inViewPort (el) ) { | |
return; | |
} | |
if (! el.classList.has('loaded')) { | |
return; | |
} | |
var context = sectionEl.getElementsByTagName('noscript') ? contextEls[0].textContent || contextEls[0].innerHTML : ''; | |
if (context) { | |
sectionEl.innerHTML = ''; | |
sectionEl.insertAdjacentHTML('beforeend', context); | |
sectionEl.classList.remove('lazyload'); | |
} | |
} | |
window.addEventListener('load', function() { | |
sectionEls.map(lazyloadSection); | |
}); | |
window.addEventListener('scroll', function() { | |
sectionEls.map(lazyloadSection); | |
}); | |
} | |
</script> | |
<?php | |
$content .= ob_get_clean(); | |
return $content; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment