Skip to Content
Menu

lazy_img()

Lazy-load images below the fold to optimize page load time.

PHP March 15, 2018

Usage

PHP
nebula()->lazy_img($src, $attributes)

Parameters

$src
(Required) (String) The path to the image
Default: None

$attributes
(Optional) (String) Any additional attributes to add to the img tag
Default: None

Parameter Notes

The $attributes tag is simply a string of any additional attribute tags to add. See examples below.

Request or provide clarification »

Examples

Lazy load an image with only a path

PHP
<?php nebula()->lazy_img('//placehold.it/1200x800'); ?>

Lazy load an image with additional attributes

PHP
<?php nebula()->lazy_img('//placehold.it/1200x800', 'class="cool-image" title="Pinckney Hugo Group" alt="Logo"'); ?>

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

This is a convenient alias of lazy_load().

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

This uses JavaScript to load images after the page has finished loading. Any images above the fold will be loaded immediately and any below the fold will wait for the user to scroll. These images are loaded in <noscript> tags so if JavaScript is not available, the images 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.

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 903.

    No Hooks

    This function does not have any filters or actions available. Request one?
    PHP
            public function lazy_img($src=false, $attributes=''){
                $this->lazy_load('<img src="' . $src . '" ' . $attributes . ' loading="lazy" />');
            }
    

    Override

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