Skip to Content
Menu

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


Lazy Loaded with nebula()->lazy_img()

Lazy Loaded with nebula()->lazy_img()

Not lazy loaded

Lazy Loaded with nebula()->lazy_load()

Lazy Loaded with native browser lazy loading attribute

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().

Lazy Loaded with "nebula-lazy" class

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:

Was this page helpful? Yes No


    A feedback message is required to submit this form.


    Please check that you have entered a valid email address.

    Enter your email address if you would like a response.

    Thank you for your feedback!

    Source File

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

    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_background_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?