0

I am developing a one page website and I would like to load in each section when the window scrolls to that specific section. Now I know you can lazyload images but I want to lazy load the entire section. The only way I think it would be possible is if I put my html code into jQuery then load it in when the scroll position is reached. But I would prefer not to do this.

This is a wordpress website and I am loading each page through into the homepage using

<?php require_once(''); ?>

so my page is layed out something like this

<?php get_header(); ?>

<?php require_once('section_one.php'); ?>

<?php require_once('section_two.php'); ?>

<?php get_footer(); ?>

So could I use php to only load these sections in when the scroll position is reached or is there a better way with jQuery? Also I want web crawlers etc to still be able to see my whole page. So if jQuery is disabled I want the full page to show. Any guidance or tutorials on this would be very helpful thanks

Reece
  • 2,581
  • 10
  • 42
  • 90

2 Answers2

2

Create a method in controller that will render a sub-view based on the section number and return you the HTML. Or in your case create a file that will accept a GET request with section number, and render the output of needed section file as its done in most PHP frameworks (see below). That way you can make AJAX request when scrolling position is of necessary value, and insert returned HTML into the page.

<?php
$section_number = $_GET['section'];

ob_start();
if(file_exists(__DIR__ . 'section_' . $section_number . '.php')) {
    include(__DIR__ . 'section_' . $section_number . '.php');
    $var=ob_get_contents(); 
    ob_end_clean();
    echo $var;
}

echo '';

Render PHP file into string variable

Daniel Protopopov
  • 6,778
  • 3
  • 23
  • 39
0

May I suggest that you load the content and hide it with CSS instead? And then make a scroll spy solution to display the content when the section enters viewport? Why force someone to wait while the contents loads?

Kidkie
  • 83
  • 1
  • 9