Skip to Content

lazy_load()

Lazy-load any HTML below the fold to optimize page load time.

PHP May 14, 2020

Usage

PHP
nebula()->lazy_load($html)

Parameters

$html
(Required) (String) The HTML to lazy load
Default: None

Request or provide clarification »

Examples

PHP
nebula()->lazy_load('<img src="//placehold.it/1234x2345" />');

Demo


Large image loaded normally (not lazy-loaded).

This should appear in a Lighthouse audit under Performance > Opportunities > Offscreen images > View Details

Large image loaded using lazy-load.

Despite being very similar to the previous large image, it will not appear in the same Lighthouse audit.

Lazy loading a background image with the .lazy-load class

This should also not appear in the same Lighthouse audit as above.

Iframe loaded using lazy_iframe().

Additional Notes

Note: this function does not need to use echo as it prints immediately.

This uses JavaScript to load HTML after the page has finished loading. Any element above the fold will be loaded immediately and any below the fold will wait for the user to scroll. This HTML is loaded in <noscript> tags so if JavaScript is not available, the elements will load as normal (including extra attributes).

A positioning element is added so the offset top can be detected (since <noscript>) tags do not have positioning. This element is removed after it is no longer needed.

The following image was placed in the content editor:

Source File

Located in /libs/Optimization.php on line 830.

No Hooks

This function does not have any filters or actions available. Request one?
PHP
        public function lazy_load($html=''){
            //Ignore lazy loading wrappers on AJAX requests
            if ( $this->is_ajax_or_rest_request() ){
                echo $html;
                return false;
            }

            ?>
            <samp class="nebula-lazy-position" style="display: block;"></samp>
            <noscript class="nebula-lazy">
                <?php echo $html; ?>
            </noscript>
            <?php
        }

Override

This function can not be short-circuited with an override filter. Request one?