Skip to main content

Cool Method For Deferring Loading Of Images In WordPress

By August 4, 2017Blog, CMS, Javascript, jQuery, PHP, Wordpress
WordPress Tutorials by Allure Web Solutions

In the post I show an interesting method for deferring loading of images using PHP and jQuery within a WordPress environment. However, this method can be applied to any environment or web app.

The inspiration for this method came while I was searching for a way to defer image loading for my flip animation effect. In my scenario, I load all WordPress posts into an isotope grid, with the front of the grid item showing the post title and content, while the back of the grid item (after the flip effect) shows the image. Since the image isn’t visible until the user hovers over the grid item, there’s no point in having it slow down the page.

The PHP (Inside Post Loop)

// generate featured image
$args = array(
	'class' => 'post-image',
);

$post_image = get_the_post_thumbnail( get_the_ID(), 'medium', $args );

// display deferred image
<img class="deferred-image" data-image="<?php esc_html( $post_image ); ?>">

The Javascript (jQuery)

$(window).on('load', function () {
    var images = $('.deferred-image'),
        image;
    images.each(function () {
        image = $(this).attr('data-image');
        if (image) {
            $(this).replaceWith(image);
        }
    });
});

Explanation

What’s going on here is pretty simple. Inside our post loop we create a placeholder image that contains the actual image code inside the data-image attribute. This is one way to pay the necessary code we need to our Javascript. An alternative and faster method would be to use the wp_localize_script() function of WordPress to pass PHP data as a variable to our javascript. The placeholder image is much smaller than an actual image, so it loads quickly on the page.

We then use jQuery to do the magic, once the page has finished loading. We find all of our placeholder images and replace them with the full image code we passed in the data-image attribute. Since this happens after the page has fully loaded $(window).on('load', function(){...}) the slow loading of images no longer affects what the user immediately sees when he land on our page.

allure

Author allure

More posts by allure

Leave a Reply

Designed by

best down free | web phu nu so | toc dep 2017